So I am relatively new to C++ so pointers is a concept I am still getting used to. I have a class called Node with two Node* called left
and right
. In a recursive method, I pass the reference to a Node's left
field:
Node left (num); node->left = &left;
However, when I go back to traverse this Node, num
has a huge number in it and my program crashes. 开发者_如何学PythonI also tried this method node->left = new Node(num);
and it worked perfectly fine. What is the difference between each method, and why does one work while the other does not?
When you declare Node left (num)
, the space for left
is allocated on the local stack. That memory gets trashed (left
goes out of scope) when you return from the method. The second method allocates space for the (anonymous) node from the heap. This is unaffected by calls and returns from methods. You could also modify your first version to: Node *left = new Node(num);
.
精彩评论