Pointer cannot be reset to NULL within function

Asked

Viewed 94 times

3

Hello, folks! I was studying binary trees and needed to create a function that would remove any knot and its children. However, when I did this function with the return /1/ the node has not been removed. Copying the return of another function from my tree, I wrote the return /2/, replacing the /1/. My question is, according to just this piece of code, is there a reason why /1/ not work?

Node * remover(Node *root, int valor){
if(root == NULL){
    cout<<"Elemento não encontrado."<<endl; 
}
else{
    if(root->data == valor){
        root = NULL; // isso não modifica o ponteiro? Por quê?
        cout<<"Elemento removido!"<<endl;
        return root;
    }
    if(root->data > valor){
        /* 1 */ //remover(root->left,valor); não funciona
        /* 2 */root->left = remover(root->left,valor); // funciona
        return root;
    }
    if(root->data < valor){
        /* 1 */ //remover(root->right,valor);  não funciona
        /* 2 */root->right = remover(root->right,valor); // funciona        
        return root;        
    }
}
}

Consequently, why this part does not work ?:

    if(root->data == valor){
        root = NULL; // isso não modifica o ponteiro? Por quê?
        cout<<"Elemento removido!"<<endl;
        return root;
    }

Thanks for the help!

1 answer

2

When you do root = NULL, you are modifying the value of the local variable root. If you want a function to receive a pointer as a parameter and modify it, you need a pointer to a pointer.

The signature of your function would look like this:

Node * remover(Node **root, int valor);

and the line that currently doesn’t work would look like this:

*root = NULL;

By the way, unless you have good reason not to, prefer nullptr to represent no value. This is the null constant that provides C++ typing security (other than NULL, which is simply a nickname for the constant 0). For this, make sure you are compiling in C++11 mode.

  • 1

    Alternatively you can also use a pointer reference (Node *&root).

  • 1

    @Pablo, it had already crossed my mind that this would be some problem related to the fact that I n used a pointer for pointer, since I saw other trees on the internet that used this type of parameter. But since I don’t know much about pointers I wasn’t sure if that’s what it was. I will study a little more to learn how to deal with it and thank you very much for the answer and the tip on the nullptr, helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.