为什么此循环不检测空指针?
Why doesn't this loop detect null pointer?
这是我的代码:
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;
}
相关文章:
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 运行时错误:引用绑定到类型为"int"的空指针
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 为什么我在空指针错误(链表)中获取成员访问权限
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 成员访问是否在空指针上定义C++?
- 尝试将对象插入空指针数组时出现分段错误
- 为什么我们需要在 C++ 中检查空指针,而在 Java 中不需要?
- 是否允许向空指针添加零?
- 为什么 C 样式字符串的工作空指针检查不?
- 在函数内初始化无符号字符指针将返回空指针
- 为什么多维数组中的空字符串文本衰减为空指针?
- C++ 取消引用指向矢量的空指针时的分段错误
- 错误 C6011:取消引用空指针"NAME"。C++
- cppcheck取消引用空指针
- 打印空指针时,std::cout 可以打印 "NULL" 而不是 0 吗?
- 未检测到的空指针
- "空指针已通过",用于检测轮廓
- 为什么此循环不检测空指针?