c++ - 如何使用未初始化的指针修复 C++ 中的 C4700 警告?

标签 c++ visual-studio pointers struct warnings

我已经通读了许多以前关于 C4700 的帖子,但我似乎找不到解决我的问题的办法。

我写了一个小脚本来演示结构指针:

struct foo
{
    int * bar;
};

#include<iostream>
using namespace std;
int main()
{
    foo * fooptr;
    int * num;
    *num = 25;
    *fooptr->bar = *num;
    cout << "now fooptr points to a foo struct whose bar points to: " << *fooptr->bar;

    fooptr->bar = num;
    cout <<"now fooptr's struct's bar shares memory address with num at " <<num;

    return 0;
}

当我编译它时,我收到两个 C4700 警告,因为使用了未初始化的局部变量 num 和 fooptr。 我继续将两者都初始化为 NULL,因此编译器错误消失了,但毫不奇怪我得到了一个异常:

testing.exe 中 0x00265DF7 处的未处理异常:0xC0000005:访问冲突写入位置 0x00000000。

你看我一直认为当我不初始化这些指针时,它们会自动用随机地址初始化(就像未初始化的整数/字符/ double 将被分配为垃圾一样)——所以不应该是这样吗?

如果在这种情况下初始化确实是绝对必要的(为什么?),那么这个问题有没有简单的解决方法?

最佳答案

代替

int *num; // num points to somewhere random
*num = 25; // writing somewhere random makes zero sense
           // and if your OS allowed you to do it, you would
           // crash your computer very often.

你必须写

int num = 25;
int *pnum = &num; // pnum is a pointer to int which has been
                  // initialized with the address of num

struct 的内容也是如此。

关于c++ - 如何使用未初始化的指针修复 C++ 中的 C4700 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963830/

相关文章:

c++ - Jenkins 上的 Coverity 有什么替代品吗?

c - C中ListNode中的指针

c - 连接两个字符串时出现段错误

c++ - 使用整数运算的浮点加法

c++ - Stack在STL中是如何实现的?

asp.net-mvc - 在 Visual Studio 中插入替换字符的最快方法

c++ - 查找内存违规/泄漏

从指针复制地址

c++ - Linux g++编译错误: error: expected ',' or '...' before '||' token

c++ - 通过类的模板参数特化成员模板结构