-4

I want to access and element of an array that is within a struct using a pointer how do I do it ?

int int_set_lookup(struct int_set * this, int item){
Tarik
  • 10,810
  • 2
  • 26
  • 40
user2562455
  • 33
  • 1
  • 9

3 Answers3

1

Assuming the call is setup and called like this:

struct int_set this[10];
int_set_lookup(this, 5);

the function int_set_lookup() can directly lookup the item:

int int_set_lookup(struct int_set* this, int item)
{
    /* where x is the item in the struct you want to lookup */
   return this[item].x;

    /* or, if int_set has an array member y, this accesses
       the 0th element of y in the item'th element of this */
    return this[item].y[0];
}
Chad
  • 18,706
  • 4
  • 46
  • 63
1

I assume the array contained within the struct is "a" and p is the pointer to the struct:

p->a[3]
Tarik
  • 10,810
  • 2
  • 26
  • 40
1

You have to use arrow operator ->

For example , p is a pointer to a struct s1 , then

#include <stdio.h>

int main(void) {        
   struct s{
    int a[10]; // array within struct 
   };    
  struct s s1 ;
  s1.a[0] = 1 ; // access array within struct using strct variable 
  struct s *p = &s1 ;  // pointer to struct
  printf("%d", p->a[0]);//via pointer to struct, access 0th array element of array member

  return 0;
}

a[0] is accessed by p->a[0] ;

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Subbu
  • 2,063
  • 4
  • 29
  • 42