简体   繁体   中英

Unexpected Pointer behavior

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM