【发布时间】:2021-12-24 15:39:31
【问题描述】:
您能否解释一下,为什么这个程序有效:
#include<stdio.h>
int main()
{
struct first{
char *name;
int a;
};
struct second{
struct first *second;
int z;
};
struct first *FIRST, C;
FIRST = &C;
struct second *SECOND, b;
SECOND = &b;
SECOND->second->a = 9;
printf("%d", SECOND->second->a);
return 0;
}
虽然不是这样:
#include<stdio.h>
int main()
{
struct first{
char *name;
int a;
};
struct second{
struct first *second;
int z;
};
//struct first *FIRST, C;
//FIRST = &C;
struct second *SECOND, b;
SECOND = &b;
SECOND->second->a = 9;
printf("%d", SECOND->second->a);
return 0;
}
简而言之,你能告诉我为什么我需要在上面的代码中添加这两个注释掉的行吗?我是这个领域的初学者。所以,如果你能帮助我,那就太好了。
提前致谢!
【问题讨论】:
-
您的第一个代码也不起作用。
SECOND->second无处可去,所以SECOND->second->a = 9;是未定义的行为。你可能忘记了SECOND->second = FIRST;。始终读取编译器输出:godbolt.org/z/zrT87r3W7 -
这两个例子都不正确,您没有初始化指针以指向有效的东西。查看链接的副本以及What is undefined behavior and how does it work?
标签: c pointers struct initialization undefined-behavior