0 c pointers undefined-behavior
我不太了解 C 编程指针,我尝试在互联网上搜索有关使用与结构相关的简单指针的信息。我有这个简单的程序:
#include <stdio.h>
typedef struct
{
int ia;
int ib;
} num;
int main()
{
num *pn;
//int a = 4;
pn->ia = 5;
printf("Hello, I made it this far!\n");
pn->ib = 10;
pn->ia = pn->ib;
printf("num = %d\n", pn->ia);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我取消注释未使用的整数 'int a = 4;' 之前,此代码不起作用
我在 Windows 10 上使用 gcc 32 位还是 64 位似乎无关紧要。
我想学习以正确的方式做到这一点,我不相信一个未使用的变量应该使它起作用!
您pn的未初始化。您的程序调用了未定义的行为并且完全错误
您需要以静态或动态方式初始化它。
num nl;
num *np = &nl;
Run Code Online (Sandbox Code Playgroud)
或者
num *np = malloc(sizeof(*np));
Run Code Online (Sandbox Code Playgroud)