c - 结构指针总是被初始化为 nil

标签 c pointers struct

我遇到这个问题,默认情况下我的结构指针总是初始化为 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/

相关文章:

c - 嵌入式软件 : Exception occurs when calling function inside a task

c - 如何防止 gcc 优化器产生不正确的位操作?

无法解析共享库中的符号,但未给出符号名称

c - 链表指针问题

c - 实现我自己的系统调用

c - 在 C 中,是否允许将某种类型的指针直接转换为另一种类型的指针?

c - 如何将结构初始化为安全值

c++ - 模板类/结构组合的好方法

C++:以最简单和最干净的方式将值写入文件?

C++:很少改变大小的大型动态结构数组,是否需要 Vector?