Reputation: 1197
I am confused with what exactly goes wrong in the following demo code. I expected that the next would keep pointing to the next element in the chain until reached end. However, I get EXE_BAD_ADDESS
error. I guess I am missing something in the recursive pointer assignment.
template <class T>
struct Node {
Node *left, *right, *parent;
int height;
T value;
// constructor
Node(T val)
: value(val){
height = 0;
left = right = NULL;
}
};
template <class T>
void assignToNext(Node<T> *n, Node<T> *next){
// base case
if (n == NULL)
return;
// else assign to this node and check for next
next = n;
assignToNext(n->left, next);
}
And then in the main:
Node<int> a(1);
a.left = new Node<int>(2);
a.left->left = new Node<int>(3);
a.left->left->left = new Node<int>(4);
a.left->left->left->left = new Node<int>(5);
Node<int> *last = NULL;
assignToNext(&a, last);
std::cout << last->value << std::endl; // I get EXE_BAD_ADDRESS error
Thanks in advance, Nikhil
Upvotes: 3
Views: 108
Reputation: 609
assignToNext(&a, last);
This code can't modify local variable Node<int> *last
's value. You just passed NULL
to parameter Node<T> *next
. So last
's value is still NULL
and you got error. If you want modify pointer's value, use double pointer.
Like,
void assignToNext(Node<T> *n, Node<T> **next);
assignToNext(&a, &last);
Upvotes: 2
Reputation: 7960
void assignToNext(Node<T> *n, Node<T> *next){
-->
void assignToNext(Node<T> *n, Node<T> *&next){
// note the &
Otherwise the original pointer isn't updated and stays NULL.
Upvotes: 3