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

时间:2021-05-16 14:32:10
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

当我这样做时,我会遇到分段错误。请指导如何执行此操作

1 个解决方案

#1


2  

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

引用kabhis评论

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 ...

等等 ...

#1


2  

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

引用kabhis评论

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 ...

等等 ...