为什么此循环不检测空指针?

Why doesn't this loop detect null pointer?

本文关键字:空指针 检测 循环 为什么      更新时间:2023-10-16

这是我的代码:

while(node) {
    cout<<node->getDiameter();
    node=node->stepAbove();
}

这些是方法:

Node* Node::stepAbove() {
    return this->above;
}
int Node::getDiameter() {
    return this->r;
}

但 while 循环会导致访问冲突,因为循环不会检测到空指针。调试时,它指向一个地址"0xcccccccc",该地址没有任何定义...有什么建议问题出在哪里吗?

编辑:忘记发布我的构造函数是:

Node(int x=0) {
    this->above=nullptr;
    this->r=x;
}

uninitialized指针和null指针之间存在差异C++

struct node
{
};
int main()
{
    node *n1 = 0;
    node *n2;
    if(!n1)
        std::cout << "n1 points to the NULL";
    if(!n2)
        std::cout << "n2 points to the NULL";
}

尝试运行此代码,您将看到不会打印指向 NULL 的 n2。你想知道为什么吗?那是因为n1已被明确指向,但我对n2没有做同样的事情。С++ 标准没有指定未初始化的指针应包含的地址。在那里,0xcccccccc似乎是编译器选择作为调试模式默认地址的地址。

在构造函数中,将未由构造函数参数初始化的字段设置为 NULL,例如:

Node::Node(float radius) 
{
    above = NULL;
    r = radius;
}