When to use double pointers?

85 views Asked by At

I saw this working code to converting a tree to its mirror.

struct node* mir(struct node *root)
{
    if(root)
    {

    struct node * temp;
    mir(root->left);
    mir(root->right);
    temp=root->left;
    root->left=root->right;
    root->right=temp;
}

Should not be there mir(struct node **) like we have in linked list?

1

There are 1 answers

0
Arjun Sreedharan On

All calls in C are call by value, which means the called functions cannot change the value of the argument in the caller's context. The called function receives just a copy of the arguments. However, you can effectively bypass this by passing a pointer to your variable, and then modifying its dereferenced state. What if the variable you want to change is a pointer? You pass a pointer to a pointer.

struct node* mir(struct node *root);
struct node* mir2(struct node **root);
...
/* following cannot change value of root */
x = mir(root);
/* following may change value of root */
x = mir2(&root);