关于二叉树上下文中NULL指针的澄清

Clarification regarding NULL pointers in context of Binary Tree

本文关键字:指针 NULL 二叉树 上下文      更新时间:2023-10-16

我有一个这样的数据结构:

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->leftp->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。它是pright也是如此。这是因为您将它们分配给p:

p->left = p->right = p;

因此,当您执行p->left->left时,您正在执行p->left,从而执行p。这里有一个圆形指针。p指向自己的实例

赋值p->left = p->right = p会将p->leftp->right赋值为p

不涉及"给予内存"。

p->leftp->right都包含与p相同的地址。因此,p->leftp->rightp都指向同一个对象。