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?
A pointer is a box that can hold the address of an object
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
You say
That can work, becuase the box tmp2 points somewhere valid