简体   繁体   中英

What is the difference between address of pointer and double pointer

I have this simple code of node.c :

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int x;
    struct Node *next;
} Node;

void unshift(Node **root, int value)
{
    Node *newNode = malloc(sizeof(Node));
    newNode->x = value;
    newNode->next = *root;

    *root = newNode;
}

//doesn't work if address of pointer is passed to unshift()
void foo(Node *root)
{
    if (root == NULL)
    {
        //pass address of pointer 
        unshift(&root, 4);
    }
}

//works with double pointer passed to unshift()
void bar(Node **root)
{
    if (*root == NULL)
    {
        //pass double pointer
        unshift(root, 4);
    }
}

int main()
{
    Node *root = NULL;

    //works
    // bar(&root);
    // printf("%p\n", root);

    //does not work
    foo(root);
    printf("%p\n", root);
}

Now there is a function insert(Node **root, int value) , which takes double pointer to root in order to change it (the newly created node will itself become a root). So obviously I can pass type Node ** either way -> double pointer, or address of pointer. I do so in 2 separate function -> foo(Node*) and bar(Node**) . In foo I am thus passing address of the argument whereas in bar I simply pass its argument.

The issue is, only the bar() with double pointer will actually change the root pointer from main. The foo() function will not, even if passing the right datatype. That is, after call with foo() , the pointer root is nil (still null pointer as in declaration), whereas after bar() the pointer really changed . So why does compiler treats the addressof and pointer differently even though both are passing the same data? And why does not foo() also change the root pointer?

It is not "the same data". In foo , &root is the address of the formal argument root in foo , but in bar you are passing the address of the variable from main . In other words, the value is changed in foo but that change is lost when foo returns because it did not update the value in main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM