Search code examples
c++pointersreferenceinitialization

what's the difference between the two ways of initializing a pointer?


when I do leetcode, and I try to initialize pointers in this way

ListNode *node1,*node2;
ListNode *p1=node1,*p2=node2;

And it gave me a member access within null pointer error in my following logic.

while(head) {
    if(head->val<x) p1=p1->next=head;
}

But if I change the initialization to this:

ListNode node1,node2;
ListNode *p1=&node1,*p2=&node2;

There will be no error, so, what's the difference between the two initialization ways?


Solution

  • ListNode *node1,*node2;
    

    These two are pointers. They are default-initialised, which for pointer means uninitialised. They don't point to anything, and the behaviour of a program reading the uninitialised values would be undefined.

    ListNode *p1=node1,*p2=node2;
    

    These two are another pair of pointers. They are initialised with by copying the values of the previous pointers, so they would point to the same objects. But the previous two pointers were uninitialised. The behaviour of the program is undefined. Don't read uninitialised values.


    ListNode node1,node2;
    

    These two are not pointers (assuming ListNode is not an alias of a pointer type). They are also default-initialised, which might mean uninitialised depending on how the ListNode type is defined.

    ListNode *p1=&node1,*p2=&node2;
    

    & is the addressof operator. It yields the address of the operand. These two pointers are initialized with the addresses of the previously declared objects i.e. they point to those objects. The (possibly) uninitialised values of those objects is not read at all. There is no undefined behaviour involved.

    Note that if head in head->val<x points to one of node1 or node2, and if those nodes are indeed still uninitialised, then the second program also suffers from undefined behaviour.