Doubt about pointers and return of functions

0

Hello everyone. I would like to know why the function below would need a pointer to the pointer, in this case a **root , so that the line / 1 / could modify the *root , while the line / 2 / can modify it without having to resort to it. What is the difference between:

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

and

root = NULL; ?

Are the two not trying to modify the pointer without using a pointer? So the two should not 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;        
}
}
}
    
asked by anonymous 26.12.2015 / 23:47

1 answer

0

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

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

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

    
26.12.2015 / 23:54