c - 谁在堆栈上的结构中初始化 char 指针

标签 c pointers nullpointerexception

众所周知,栈上的东西默认是不初始化的。我试图用堆栈上的结构来证明这一点,但出乎意料的是我的指针被初始化为空,但为什么呢?什么在初始化这个指针?

#include <stdio.h>
#include <string.h>

struct strustri {
    int var1;
    char *var2;
};

int main()
{
    struct strustri test1 = {
            .var1 = 12,
            .var2 = "Teststring",
    };
    struct strustri test2;

    printf("test1.var1 is %d\n", test1.var1);
    printf("test2.var1 is %d\n", test2.var1);

    printf("test1.var2 points to %p\n", test1.var2);
    printf("test2.var2 points to %p\n", test2.var2);
    return 1;
}

这是我机器上的输出(Ubuntu 12.10):

test1.var1 is 12
test2.var1 is -1271814320
test1.var2 points to 0x400634
test2.var2 points to (nil)

我多次运行示例。我每次都得到 var1 的另一个值,但是 var2 总是指向零(空指针)...

最佳答案

没有任何东西正在初始化它。

这只是您堆栈中碰巧出现的任何垃圾的产物。切换变量声明的顺序,或者添加更多的局部变量,你会得到不同的结果。

关于c - 谁在堆栈上的结构中初始化 char 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14704764/

相关文章:

c - 除了邮件搜索技术之外,如何获取邮箱中未见过/未读的电子邮件

将一定数量的字符从一个指针复制到另一个指针

android - 旋转后 fragment 字段为空

java - 启动连接池时数据源出现NullPointerException

一旦退出函数,复制字符指针就没有效果,预期是垃圾值,但会恢复以前的地址

c - 它是可移植的编译库吗?

c++ - 从函数返回唯一的 void 指针

c - 使用函数增加动态数组大小;无错误,下一个尺寸无效(快)

c++ - 访问堆成员和堆栈对象之间的性能差异?

java - 在 java 中调用方法时出现 NullPointerException