typedef struct
{
unsigned int a;
unsigned char b[10];
unsigned char c;
}acc1;
typedef struct
{
unsigned char z[10];
acc1 *x,y[10];
}acc2;
extern acc2 p[2];
我想从struct acc1
数组acc2
访问p[2]
个变量。
我这样做时会出现分段错误。请指导如何执行此操作
答案 0 :(得分:2)
要访问y
的元素,请执行以下操作:
char c = p[some index between 0 and 1].y[some index between 0 and 9].c
要访问x
引用的元素,请执行以下操作:
size_t i = some index between 0 and 1;
p[i].x = malloc(somenumber_of_elements * sizeof *p[i].x);
if (NULL == p[i].x)
{
abort(); /* Failure to allocate memory. */
}
char c = p[i].x[some index less then somenumber_of_elements].c;
参考 kabhis 评论
p [0] .x-> c是不正确的?
假设上面的分配somenumber_of_elements
大0
,那么:
char c = p[i].x[0].c;
相当于
char c = p[i].x->c;
和somenumber_of_elements
更大1
char c = p[i].x[1].c;
相当于
char c = (p[i].x + 1)->c;
依旧......