如何使用指针和数组访问嵌套结构?

时间:2015-06-27 08:37:11

标签: c arrays struct

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]个变量。

我这样做时会出现分段错误。请指导如何执行此操作

1 个答案:

答案 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_elements0,那么:

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;

依旧......