我想使用指针访问结构内的数组的元素,我该怎么做?
int int_set_lookup(struct int_set * this, int item){
假设呼叫已建立并像这样调用:
struct int_set this[10];
int_set_lookup(this, 5);
该函数int_set_lookup()
可以直接查找项目:
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];
}
我假设结构中包含的数组是“a”,p 是指向结构的指针:
p->a[3]
您必须使用箭头运算符->
例如,p
是一个指向结构的指针s1
,那么
#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]
被访问p->a[0]
;