C++ Linked list Pointer to pointer

Is anyone able to explain how pointer to pointer works in this linked list implementation? Can't seem to fully understand, especially with "node=&((*node)->next);". How does it all come together? Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum=0;
        ListNode *l3=NULL;
        ListNode **node=&l3;
        while(l1!=NULL||l2!=NULL||sum>0)
        {
            if(l1!=NULL)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL)
            {
                sum+=l2->val;
                l2=l2->next;
            }
            (*node)=new ListNode(sum%10);
            sum/=10;
            node=&((*node)->next);
        }        
        return l3;
    }
a pointer to a pointer just basically stores the address of another pointer.

what you have posted is annoying to look at for sure lol. but this line node=&((*node)->next); is just dereferencing the pp then -> is also dereferencing the underlying pointer object then the & means the address of that value.

this should make it easier to understand. untested but shows no errors

1
2
3
4
5
6
7
8
9
10
11
12
struct a {

	int next;
};

a* b;

a** c = &b;

int* d = &(*c)->next;

b->next == (*c)->next


so in other words b is a pointer to a struct of type a. c is a pointer that holds the address of pointer b. d holds the pointer to the of the value of struct member next contained within b. but as the above shows dereferenced c is equal to b. any changes made to dereferenced c will affect b bc its the same thing

on that note dereferencing d and changing the value would also affect the next variable contained within b.
Last edited on
Topic archived. No new replies allowed.