分配内存后,struct成员指针仍为null

时间:2016-05-03 12:00:23

标签: c++ struct null

我有两个结构代表二叉搜索树和bst的节点。第一次输出符合预期时调用add方法:tree is null,但为什么它仍然是:tree is null在我第二次调用它之后?

如果我将参数作为参数发送到整个bst的add方法,它就可以了。

#include <iostream>

using namespace std;

struct node
{
    int data;
    node* right = NULL;
    node* left  = NULL;
};

struct bst
{
    node* root = NULL;
};



void add(node* tree) 
{

    if (tree == NULL)
    {
        cout << "Tree is NULL "<<endl;
        tree = new node;
    }
    else cout << "Not NULL"<<endl;
}

int main()
{
    bst* tree = new bst;
    add(tree->root);
    add(tree->root);
    system("pause");
    return 0;

}

2 个答案:

答案 0 :(得分:1)

除非您将树声明为指针的地址,否则您无法将树传递回函数:

    void add(node** tree) {
        if ( tree == NULL ) {
          return;
        }
        if (*tree == NULL) {
          cout << "Tree is NULL " << endl;
          *tree = new node;
        } else {
          cout << "Not NULL" << endl;
        }       
    }

答案 1 :(得分:0)

您正在传递节点本身而不是其地址。 尝试

void add(node** tree)
{
  if (*tree == NULL)
  {
      cout << "Tree is NULL "<<endl;
      *tree = new node;
  }
  else cout << "Not NULL"<<endl;
}

int main()
{
  bst* tree = new bst;
  add(&(tree->root));
  add(&(tree->root));
  system("pause");
  return 0;
}