【问题标题】:struct member pointer still null after allocating memory [duplicate]分配内存后结构成员指针仍然为空[重复]
【发布时间】:2016-05-03 12:00:23
【问题描述】:

我有两个结构,分别代表二叉搜索树的一个节点和一个 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;

}

【问题讨论】:

  • 这不是 C。在 C++ 中,您不应使用宏 NULL,而应使用 nullptr 关键字。
  • 您没有通过引用传递tree 指针,正在处理重复...
  • 你是按值传递指针
  • 这已经被问过很多次了...

标签: c++ struct null


【解决方案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;
        }       
    }

【讨论】:

    【解决方案2】:

    您传递的是节点本身而不是其地址。 试试

    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;
    }
    

    【讨论】:

    • 他其实是在传递节点的地址。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多