Why we use “&(*” statement when double pointer to struct is an argument of a function?

前端 未结 3 724
萌比男神i
萌比男神i 2021-01-29 08:09
void instert(NODE**root, int value)
{
    ...
    insert(&(*root)->left,value);
    ...
}

void search(NODE*root, int value)
{
    ...
    search(root->left, v         


        
3条回答
  •  不知归路
    2021-01-29 08:50

    An extra level of indirection is added to insert function so that it could modify the pointer. This is not necessary in case of the search function, because it never modifies the pointer passed to it.

    Specifically, there needs to be a place in the insert function that does something like this:

    *root = malloc(sizeof(NODE));
    (*root)->left = NULL;
    (*root)->right = NULL;
    (*root)->value = value;
    

    This would modify the pointer which is pointed to by the pointer to pointer.

    Note that it is possible to avoid this extra level of indirection by returning the new value of the pointer from insert, like this:

    NODE* insert(NODE*root, int value) {
        ...
        root->left = insert(root->left, value);
        ...
    }
    

    However, this changes the way in which all callers must call insert, including the top-level caller: rather than writing

    insert(&root, value);
    

    he would be forced to write

    root = insert(root, value);
    

提交回复
热议问题