c++ - 未检测到空指针
问题描述
我是 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 是否指向任何内容。
解决方案
在您的示例中,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
}
推荐阅读
- snipcart - Snipcart 或其他类似解决方案
- java - 我的 editor_layout_problem - 2 如何在 scoll 或 listview 中多次显示不同的片段
- java - Android RecyclerView 仅在关闭并重新启动应用后显示项目
- angular - 如何在 Spring MVC 中为 Angular 前端生成下载文件弹出窗口?
- r - 带假人的非线性最小二乘法
- mysql - MySQL Multiple INNER JOIN + GROUP BY 未按预期工作
- javascript - 如何更改 vuetify 数据表中单个按钮的属性?
- android - 有什么方法可以捕捉电话接听事件吗?
- javascript - 是什么导致我的代码中出现“RangeError:超出最大调用堆栈大小”?
- vue.js - Nuxt.js:管理静态生成网站的 CMS 集合