未检测到空指针

Ana*_*sia 2 c++

我是C ++的新手。我希望没有指向任何东西的两个指针将被检测为空指针。但是,这仅适用于其中之一。这些指针的物理地址有些不同-0xe00000001与0x0(此指针正确检测为空指针)。

我编写了以下代码段:

#include <iostream>
using namespace std;

struct TNode {
    TNode* Parent;  // Pointer to the parent node
    TNode* Left;  // Pointer to the left child node
    TNode* Right;  // Pointer to the right child node
    int Key;  // Some data
};

int main() {
    TNode parent;
    parent.Key = 2;
    TNode first;
    first.Key = 1;
    first.Parent = &parent;
    parent.Left = &first;
    cout << first.Left << endl; // get 0xe00000001 here
    cout << first.Right <<endl; // get 0x0

    if (first.Right == nullptr) {
        cout <<"rnull"<<endl; // rnull
    }
    if (first.Left == nullptr) {
        cout <<"lnull"<<endl; // nothing
    }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?基本上,我想找到一种方法来检查first.Left是否没有指向任何对象。

J. *_*rez 6

在你的榜样,first.Left并且first.Right是未初始化的,没有空。这意味着它们基本上包含分配它们时堆栈上的所有垃圾。访问实际值(例如,通过打印指针)实际上是未定义的行为,但是对于大多数编译器,如果它们的优化设置较低,则只会打印该垃圾。

解决方案1:为成员变量提供默认值

如果希望它们为空,则可以进行修改,TNode以确保其初始值为空:

struct TNode {
    TNode* Parent = nullptr;
    TNode* Left = nullptr;
    TNode* Right = nullptr; 
    int Key = 0;
};

int main() {
    TNode n; //Everything initialized to null or 0
}
Run Code Online (Sandbox Code Playgroud)

这将保证它们为空。

解决方案2:定义TNode()以初始化成员

另外,您也可以显式定义构造函数,以使所有内容都为空

struct TNode {
    TNode* Parent, Left, Right;
    // Everything gets default-initialized to null
    TNode() : Parent(), Left(), Right() {}
};

int main() {
    Tnode n; // Everything initialized to nullptr or 0
}
Run Code Online (Sandbox Code Playgroud)

解决方案3:使用时默认初始化

即使没有显式定义构造函数,{}在声明变量时通过将其显式初始化时,所有内容都将初始化为0(如果为指针,则为null)。

struct TNode {
    TNode* Parent, Left, Right;
    int Key;
};

int main() {

    TNode iAmUninitialized; // This one is uninitialized

    Tnode iAmInitialized{}; //This one has all it's members initialized to 0
}
Run Code Online (Sandbox Code Playgroud)