关于二叉树上下文中NULL指针的澄清
Clarification regarding NULL pointers in context of Binary Tree
我有一个这样的数据结构:
struct node
{
int count;
node *left,*right;
node(int count,node* l,node*r)
{
this->count=count;
this->left=l;
this->right=r;
}
node* update(int l,int r,int v);
};
现在我声明一个全局变量:
node* p=new node(0,NULL,NULL);
所以这个语句会导致p
有:
p->count=0;
p->left=NULL;
p->right=NULL;
我的问题是如果我写p->left=p->right=p;
会发生什么。据我所知,它将为p->left
和p->right
提供内存,它们最初是NULL。所以,它应该是:
p->left->count=0, p->left->left=NULL,p->left->right=NULL;
p->right->count=0, p->right->left=NULL,p->right->right=NULL;
但我不认为这是发生了什么,因为当我打电话update(0,9,0)
,其中l=0, r=9和v=0,它的工作很好,如果我有在调用这个之前写语句p->left=p->right=p
函数。但它不能运行,如果我评论这个语句(即它试图访问空指针值我猜)。
但我不认为这是发生了什么,因为当我调用
你是对的。实际上,p->left->left
是而不是 NULL
。它是p
。right
也是如此。这是因为您将它们分配给p
:
p->left = p->right = p;
因此,当您执行p->left->left
时,您正在执行p->left
,从而执行p
。这里有一个圆形指针。p
指向自己的实例
赋值p->left = p->right = p
会将p->left
和p->right
赋值为p
。
不涉及"给予内存"。
p->left
和p->right
都包含与p
相同的地址。因此,p->left
、p->right
和p
都指向同一个对象。
相关文章:
- 当使用通配符和null指针调用函数时,对输出的说明
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- API 返回智能指针的 std::optional 以明确指定指针可能为 null 是否有意义?
- 为什么在C++中增加指针后打印了一个值而不是 NULL/0?
- 指针永远不会在链表深层复制构造函数中达到 null
- 正在将对象指针数组初始化为NULL
- 为什么在C++中使用delete后指针不为NULL
- C++中的指针否定 (!ptr == NULL)
- 如何返回值为NULL的变量指针
- 打印空指针时,std::cout 可以打印 "NULL" 而不是 0 吗?
- 将位数组转换为 HBITMAP 后 bmBits 的 NULL 指针
- C++ 由于类析构函数中的指针设置为 NULL 而导致的内存泄漏
- 如果指针在C++为 NULL 则修改指针
- 在访问类的树层次结构中的对象时避免使用 null 指针
- if(NULL==指针)和if(指针==NULL)之间有什么区别
- 从转储中获取调用堆栈的几乎所有帧中的此指针 NULL 表明什么
- 指针 NULL 在C++中的函数
- 自动指针= NULL错误
- 如何使指针指向指针NULL
- 当我们分配指针 NULL 时会发生什么