0
 typedef struct sTree {
    int key;
    struct sTree* p;
    struct sTree* left;
    struct sTree* right;
} sTree;

typedef sTree* tree;

void treeInsert(tree* root);

int main(){
    srand((unsigned)time(NULL));
    tree *root = NULL;
    treeInsert(&root);
    return 0;
}

void treeInsert(tree* root){
    ......
}

I don't understand why I have to pass '&' when calling tree insert (&root instead of root). I've created a struct representing a node of binary tree and I declared a pointer to the root of the tree as 'tree*'. So 'root' is double pointer. The function 'treeInsert' expects a double pointer. If I pass simply 'root' it takes the value (NULL) else with the operator '&' it points correctly to the root. The problem is: passing '&root' I'm not passing a triple pointer? Can someone explain why?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    See [Is it a good idea to typedef pointers?](https://stackoverflow.com/q/750178/15168) TL;DR — the answer's NO, with a possible exception for pointers to functions. – Jonathan Leffler May 07 '20 at 04:57
  • @JohnnyMopp look at the `void treeInsert(tree* root)` fingerprint. Typedef or not, `root` is ok for that function. We don't know how that function is implemented. Let's avoid guessing. – Roberto Caboni May 07 '20 at 05:13
  • @davide is the compiler ok with passing `&root` to `treeInsert`? – Roberto Caboni May 07 '20 at 05:25

1 Answers1

0

regarding:

treeInsert(&root);

the need for the & is because the function: treeInsert() will need to modify the contents of the pointer. Without the & any assignment to that passed parameter will only change the parameter on the call stack and not the the contents of the parameter in main()

regarding:

tree *root = NULL;

Since tree is already a pointer, this results in (effectively)

tree ** root = NULL;

which will not accomplish what is needed.

A prime example of why a pointer should NOT be hidden in a typedef statement

the following proposed code is clear about what is wanted:

struct sTree 
{
    int key;
    struct sTree* p;
    struct sTree* left;
    struct sTree* right;
};

typedef struct sTree tree;

void treeInsert(tree** root);

int main( void )
{
    srand((unsigned)time(NULL));
    tree *root = NULL;
    treeInsert(&root);
    return 0;
}

void treeInsert(tree** root)
{
    tree *localroot = *root; // now 'localroot' is a pointer to the variable `root` in function: `main()`
    ......
}
user3629249
  • 16,402
  • 1
  • 16
  • 17