我遇到这个问题,默认情况下我的结构指针总是初始化为 nil
。下面是我的代码。
#include <stdio.h>
struct SomeStruct {
int x;
};
int main()
{
int array[2]; // If I change this to 1, the code works fine
struct SomeStruct *ptr;
printf("%p\n", ptr); // always prints "nil"
}
谁能解释一下这里发生了什么。具体来说,为什么将数组的大小更改为 1 会使代码运行正常。
以上是一些较大代码的一部分,我能够将问题简化为这个。稍后我需要使用 ptr
但我遇到了段错误,因为它是 nil
。
最佳答案
Can someone please explain what is going on here. Specifically, why does changing the size of array to 1 make the code run fine.
你正在使用 ptr
而没有初始化它。更改数组的大小会更改堆栈的布局,幸运的是您的代码可以“正常”执行。
I need to use ptr later but I get segmentation faults as it is nil
然后给它分配一些内存:
ptr = malloc(sizeof *ptr);
关于c - 结构指针总是被初始化为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14797326/