Home > database >  what is the difference between *root and **root?
what is the difference between *root and **root?

Time:12-05

I was iterating a tree data structure which has a pointer to its root as follows-

struct node *root;

when I have to pass reference of this root as a parameter to a function.... I have to pass it like-

calcHeight(&root);
-
-
-
//somewhere

int calcHeight(struct node **root)      // function defination is this

My question is- why do we need to pass "root" pointer as &root? can't we just pass root like--

struct node *root;
calcHeight(root);
int calcHeight(struct node *root);

CodePudding user response:

struct node * is a pointer to a struct node.
struct node ** is a pointer to a pointer to a struct node.

The reason for passing in a struct node ** could be that the function needs to modify what the struct node * is actually pointing at - which seems odd for a function named calcHeight. Had it been freeNode it could have made sense. Example:

void freeNode(struct node **headp) {
    free(*headp);
    *headp = NULL; // make the struct node * passed in point at NULL
}

Demo

Another reason could be to make the interface consistent so that one always needs to supply a struct node ** to all functions in the functions supporting struct nodes - not only those actually needing to change what the struct node * is pointing at.

CodePudding user response:

Because in calcHeight you're passing your argument by value. If you want to modify the pointed value by root you need to pass the adress of the pointer.

CodePudding user response:

First one is a pointer to node which is a structure.

struct node *root;

defines root as a variable which can store the address of a node.

Second one is a pointer to a pointer to node which is a structure.

struct node **root;

defines root as variable which can store address of another variable which has the address of a node.

why do we need to pass "root" pointer as &root?

calcHeight(&root);

C passes arguments by value, not by reference. so, you have to pass the address of root to modify the value of root.

  • Related