【发布时间】: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指针,正在处理重复... -
你是按值传递指针
-
这已经被问过很多次了...