访问嵌套的结构元素
Accessing the nested Structural Elements
#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。代码编译没有任何错误,但在输出屏幕中,它是空白的。
请给我一个访问结构 a 中元素的好方法。
请注意,结构 a 已在结构 b 中声明为指针。
这会崩溃,因为您的指针 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
#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。代码编译没有任何错误,但在输出屏幕中,它是空白的。
请给我一个访问结构 a 中元素的好方法。
请注意,结构 a 已在结构 b 中声明为指针。
这会崩溃,因为您的指针 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