Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Pointer behavior

Tags:

c++

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

like image 761
Nikhil J Joshi Avatar asked Mar 22 '26 03:03

Nikhil J Joshi


1 Answers

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.

like image 99
egur Avatar answered Mar 24 '26 17:03

egur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!