Reincarnationist
Reincarnationist

Reputation: 51

How should I get to the actual node with a pointer to pointer?

I would like to set root_1's name to be "hi", just like the output of the current output of this code, which is mentioned below. Unfortunately, it doesn't work.

struct Node 
{
    int num;
    char *name;
    struct Node *child;     
    struct Node *sibling;   
};

int main()
{

    struct Node root = {1,"hi",NULL,NULL};
    struct Node *root_0 = &root;
    struct Node **root_1 = &root_0;
    char *s = root.name; //s is now hi
    root_0 -> name = s;
    //*root_1 -> name = s;  //?????
    printf("%s\n", root_0 -> name);

    return 0;
}

Upvotes: 2

Views: 49

Answers (2)

Jon Nimrod
Jon Nimrod

Reputation: 345

It's just that * has a lower priority than ->.

*foo->bar = *(foo->bar) != (*foo)->bar.

So in your case you'd need (*root_1)->name = s;

Upvotes: 0

Blaze
Blaze

Reputation: 16876

That's not how pointers work. root_1 doesn't have a name or any other field - all it does is pointing to root. You don't have to set anything for root_0 and root_1, you can access root's name through them like this:

int main()
{

    struct Node root = { 1,"hi",NULL,NULL };
    struct Node *root_0 = &root;
    struct Node **root_1 = &root_0;

    printf("root_0: %s\n", root_0->name);
    printf("root_1: %s\n", (*root_1)->name);

    return 0;
}

This prints:

root_0: hi

root_1: hi

So in other words, (*root_1)->name is root_0->name, which is root.name. Perhaps it's less confusing if you consider that root_0->name is the same as writing (*root_0).name and (*root_1)->name is like writing (**root_1).name. You just add a * per pointer level.

Upvotes: 3

Related Questions