访问嵌套的结构元素

时间:2019-11-30 12:04:49

标签: c structure

#include<stdio.h>

struct a
{
    float n;
    int e;
};

struct b
{
    struct a *c;
}h;

int main()
{
    h.c->n=4;
    printf("%f",h.c->n);
    return 0;
}

是的,这是小代码,但是我一直在尝试访问通过结构b指示a的元素e。该代码已编译,没有任何错误,但在输出屏幕中为空白。

请建议我一种访问struct a中元素的好方法。

请注意,结构a已在结构b中声明为指针。

1 个答案:

答案 0 :(得分:2)

这将崩溃,因为从未分配您的指针c

h.c->n=4;  // pointer `c` has not been pointing to anything valid

要使其正常运行,您需要以下内容:

struct a aa;  // must allocate an item of struct `a` first
aa.n = 4;
aa.e = 0;

h.c = &aa;    // then make pointer `c` to point that that item
printf("%f",h.c->n);   // before trying to access that pointer
相关问题