简体   繁体   English

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

[英]How to access nested structure using pointer and array?

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];

I want to access struct acc1 variables from acc2 array p[2] . 我想从acc2数组p[2]访问struct acc1变量。

I'm getting segmenatation faults when I do it. 我这样做时遇到段分割错误。 Please guide on how to do this 请指导如何做

To access y 's elements do: 要访问y的元素,请执行以下操作:

char c = p[some index between 0 and 1].y[some index between 0 and 9].c

To access elements referred to by x do: 要访问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;

Referring kabhis comment 引用kabhi的评论

p[0].x->c is it not correct ? p [0] .x-> c不正确吗?

Assuming the allocation above with somenumber_of_elements greater 0 , then: 假设上面的分配的somenumber_of_elements大于0 ,则:

char c = p[i].x[0].c;

is equivalent to 相当于

char c = p[i].x->c;

and for somenumber_of_elements greater 1 对于somenumber_of_elements大于1

char c = p[i].x[1].c;

is equivalent to 相当于

char c = (p[i].x + 1)->c;

and so on ... 等等 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM