为什么根指针总是初始化为null
Why does the root pointer get initialized to null always?
我对以下代码感到非常困惑:
class Tree {
protected:
struct Node {
Node* leftSibling;
Node* rightSibling;
int value;
};
private:
Node* root;
int value;
.....
public:
void addElement(int number) {
if (root == NULL) {
printf("This is the value of the pointer %lldn",(long long)root);
printf("This is the value of the int %dn",value);
...
return;
}
printf("NOT NULLn");
}
};
int main() {
Tree curTree;
srand(time(0));
for(int i = 0;i < 40; ++i) {
curTree.addElement(rand() % 1000);
}
}
curTree
变量是主函数的局部变量,所以我希望它的成员不会初始化为0,但它们都初始化了。
否,它有未指定的内容。这些内容可能是随机内存垃圾,也可能恰好是0,这取决于之前留在其内存位置的数据。
可能只是由于代码的编译方式,包含root
的特定堆栈位置总是为0(例如,因为占用相同堆栈位置的早期局部变量最终总是为0)。但你不能依赖这种行为——在读回之前,你必须正确地初始化任何东西,否则你就进入了未定义行为的领域。
指针隐式初始化的实际默认值将取决于您使用的编译器。Visual C编译器(v2012)将自动将其初始化为等于NULL的__nullptr。请查看MSDN文档(请参阅最后一个示例)。
如果你想了解更多信息,我会查看你的编译器手册。
您不会在任何地方初始化root
,初始化它的合适位置应该是构造函数。
相关文章:
- 如何在 C++ 中使用 NULL(或 0)初始化静态字符数组
- C++,检查当我无法使用 NULL/0 时是否初始化了变量
- 链表指向 NULL,尽管我已经初始化了这个链表
- = NULL,在 c++98 中初始化非静态数据成员
- 指针类成员在通过类方法初始化后保持 NULL
- 如何将 cin>> 与初始化的字符* 一起使用为 NULL
- 初始化数组中的每个变量以'0'与将它们全部初始化为 null 相同吗?
- 用null C 初始化结构阵列
- 正在初始化指向null的专用指针数组
- C++:无法通过传递给查找器函数来重新分配 null 初始化的对象指针
- ConstexPR 用于派生类中的 null 初始化构造函数
- std::队列初始化与 NULL
- 未初始化的矢量指针不为NULL
- 使用构造函数初始化指向双击列表中NULL的指针
- 初始化char数组以容纳非null终止的字符串
- 如何用NULL(c++)初始化对的向量
- 如何初始化指向null的指针
- 初始化对话框后,子对话框的 hWnd 将重置为 NULL。
- 将char数组初始化为字符串值时,未初始化的索引被设置为null
- 指针初始化:何时给初始化的指针赋NULL值