I have the following code:
typedef struct TreeNode
{
int data;
TreeNode *lchild, *rchild;
} TreeNode;
TreeNode *CreateBTNode(TreeNode *bt) // pre-build
{
char ch;
cin >> ch;
if (ch == '#')
bt = nullptr;
else
{
bt = (TreeNode *)malloc(sizeof(TreeNode));
bt->data = ch;
bt->lchild = CreateBTNode(bt->lchild);
bt->rchild = CreateBTNode(bt->rchild);
}
return bt;
}
void DeleteBiTree(TreeNode *&bt)
{
if (!bt)
return;
DeleteBiTree(bt->lchild);
DeleteBiTree(bt->rchild);
free(bt);
bt = nullptr;
}
void PreOrder(TreeNode *bt)
{
if (bt)
{
cout << bt->data << " ";
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
int main()
{
TreeNode *tree = CreateBTNode();
TreeNode *tmp = tree;
DeleteBiTree(tree); // line 1
DeleteBiTree(tmp); // line 2
PreOrder(tree); // line 3
return 0;
}
In this code the tree and tmp have the same address. when i delete this tree using line 1 and output the tree, there is no output and it's right, but when i try to delete the tree using line 2,
there comes to a mess, why? Thanks a lot.
TreeNode *&btand notTreeNode *bt?DeleteBiTreetakes a reference to the pointer argument and modifies it. If you pass different pointers into the function, you'll modify different pointers.void f(int& a) { a = 1; } int main() { int x = 0; int y = x; f(y); cout << x; }prints '0', not '1'.cout, not C++. Please don't write code like this and don't learn this. Don't usemallocin C++.