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){
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){
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];
}
I assume the array contained within the struct is "a" and p is the pointer to the struct:
p->a[3]
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]
;