Doubts about pointer pointers and function returns

Asked

Viewed 139 times

0

Hello, folks. I’d like to know why the function below would need a pointer to pointer, in case a **root, for the line /1/ could modify the *root, while the line /2/ can modify it without having to use it. What’s the difference between:

root->right = remover(root->right,valor);

and

root = NULL;?

Aren’t the two trying to modify the pointer without using a pointer to the pointer? So, the two shouldn’t be wrong?

FUNCTION:

Node * remover(Node *root, int valor){
if(root == NULL){
cout<<"Elemento não encontrado."<<endl; 
}
else{
if(root->data == valor){
    root = NULL;
    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;        
}
}
}
  • Where are you seeing pointer pointer? I don’t understand what the doubt is. Without seeing the whole, it seems to me that the code is right.

  • I said if instead of *root I had used **root, the program would work with the /1/ line as well. I just wanted to understand why line 2 works, even using only a simple pointer, *root.

  • The function should be void there is no reason to edit a variable and return it.

1 answer

0

The first line is modifying root->right and not root. The proof of this is that if you display on the screen the address of root before and after this operation, there will be no change.

The second line tries to change (judging by semantics) the value saved in the pointer root. To change this value from the inside of a function, such a function needs the address of the variable that contains this value.

Remember: root simply stores a memory address. Changing what is in the place pointed by that address is not the same as changing that address.

  • then, in a way, the root is acting as a pointer pointer, on line 2, since it is modifying a pointer that is inside it, in case right? It would be right to think that way?

  • I don’t think it’s good to think about the semantic nuances of things like this when there is an objective answer: through root it is possible to reach right and change the value, simply because the value of right is "inside" root. It may be clearer if you remove the arrow operator and switch to the appropriate asterisks until it is clear (then put the arrow back)

Browser other questions tagged

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