I was just trying to grasp better understanding of pointers to pointers and on internet I found an example of Binary search where the developer used pointers to pointers in an insert function.
My question is:
- What edge does the below code have over other BST code which uses single pointers?
- At the end of insert function, the code uses a recursive method but I don’t understand the syntax of using
&ininsert(&(*tree)->right, item);.
The insert function looks like this:
void insert(node ** tree, node * item)
{
if(!(*tree))
{
*tree = item;
return;
}
if(item->val<(*tree)->val)
insert(&(*tree)->left, item);
else if(item->val>(*tree)->val)
insert(&(*tree)->right, item);
}
Because of this line, which assigns
treeto item if it is null, i.e., it starts a new tree.If you only took a
node*then you would not be able to assign a new value to it that would be visible from outside of the function. This is because the pointer is passed by value, so theinsertfunction would simply be modifying a copy of the original.The
->operator has a igher precedence than the&operator does, so it is passing in the address of*tree->right, i.e., thenode**next in line.