为什么当我将非 NULL 指针传递给方法时,它们似乎会转换为 NULL?(C++)

Why do non-NULL pointers seemingly convert to NULL when I pass them to a method? (C++)

本文关键字:NULL 转换 C++ 指针 为什么 方法      更新时间:2023-10-16

我有一个二叉树,我想打印出来。我的树结构是:

struct tree
{
  Node * root;
  tree() {root = NULL;}
  Node * insert(Node * n, people * pp);
  void print(Node * pp)
  {  
    if(pp==NULL)
    { cout<<"Node sent to print is null"<<endl; return;}
    print(pp->left);
    cout<<pp->p->lname<<endl;
    print(pp->right);
   }
};

总的来说,我是这样称呼的:

if(tr->root == NULL) cout<<"drat";
  tr -> print(tr->root);

我完全确定 tr->root 不是 NULL,考虑到我只是在打印之前遵循了一行。为什么我的打印方法坚持要传递空值?

您的print()函数是递归的。 它将沿着树向下移动,直到找到空叶并打印该消息。然后它将打印其余部分。

我建议以下修改:

 void print(Node * pp)
  {  
    if(pp==NULL)
    { cout<<"Node sent to print is null"<<endl; return;}
    if (pp->left) print(pp->left);
    cout<<pp->p->lname<<endl;
    if (pp->right) print(pp->right);
   }