1

我是 C++ 新手。我希望两个不指向任何内容的指针被检测为空指针。然而,这只适用于其中之一。这些指针的物理地址有些不同 - 0xe00000001 vs 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;
}

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

4

2 回答 2

5

在您的示例中,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
}

这将保证它们为空。

解决方案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
}

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

即使您没有显式定义构造函数,当您{}在声明变量时通过 put 显式初始化它时,所有内容都会初始化为 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
}
于 2019-05-04T00:05:05.457 回答
0

首先,在 C 和 C++ 中,没有指向任何内容的指针。不管指针中的值是什么,它都指向某个东西。甚至 NULL 也是指向地址“0”的指针,但我们按照惯例使用它来表示 NULL。未初始化指针的问题是它可以指向任何东西,并且任何东西都可能是非法地址,这将导致异常,或者它指向应用程序中的其他东西,如果数据被修改,将导致不受欢迎的一面-影响。

在您的情况下,第二个指针是 0x00,即 NULL。然而,第一个指针是 0x01,它不是 NULL。

于 2019-05-03T23:43:21.280 回答