Home > Mobile >  The initialization of ListNode
The initialization of ListNode

Time:03-29

I have a question about the initialization of ListNode, if I just announce a ListNode pointer, why can't I assign its next value like showed in the code.

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* tmp;
tmp->next = nullptr;// This is wrong, why is that?

ListNode* tmp2 = new ListNode(1);
tmp2->next = nullptr;// This is right, what cause that?

I just try to announce a ListNode pointer and assign its next value to nullptr. But after I announce a pointer with new function, it goes right. Why?

CodePudding user response:

A pointer is a box that can hold the address of an object

 ListNode* tmp;
 tmp->next = nullptr;// This is wrong, why is that?

Here you created the box (tmp) but did not put the address of an object in it. The second line says - "at offset 4 from the address stored in tmp please write 0", well there is no valid address in the box so this fails.

In the second example

ListNode* tmp2 = new ListNode(1);
tmp2->next = nullptr;// This is right, what cause that?

You say

"Please make a new ListNode object"
"Put its address in the box called tmp2"
"at offset 4 from the address stored in tmp2 please write 0"

That can work, becuase the box tmp2 points somewhere valid

CodePudding user response:

I just try to announce a ListNode pointer and assign its next value to nullptr

The pointer does not have any data members. It is an object of the type ListNode that has data members.

So you need an object of the type ListNode and using a pointer pointing to the object you can assign any value to the data member next of the object.

ListNode* tmp2 = new ListNode(1);
^^^^^^^^^^^^^^       ^^^^^^^^^^^
  pointer               object

As for this code snippet

ListNode* tmp;
tmp->next = nullptr;// This is wrong, why is that?

then neither object of the type Listnode exists data members of which you could change. Moreover as the pointer tmp is uninitialized and has an indeterminate value then using such a pointer to access memory results in undefined behavior.

  • Related