Reputation: 435
I have the following code snippet (regarding singly linked list) -
class Node
{
public:
int data;
Node* next;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = nullptr;
return temp;
}
int main()
{
Node* head = newNode(2);
head->next = newNode(4);
Node* p1 = head;
p1 = nullptr;
return 0;
}
Here, head
and p1
are separate variables - meaning separate memory location. So, when we do p1=nullptr
, only p1
should be effected, and not head
. And, this is what happens, when I debug the code (as seen in the image below):
But, when I do p1->next=nullptr instead of p1=nullptr, head is also effected. As shown in the image below:
p1 and head are different memory locations. Hence p1=nullptr does not effect head. But why does p1->next=nullptr effect head?
p1 points to a string of pointers and head also points to a string of pointers (p1->next->next->next... and head->next->next->next...). p1 is at the same memory location as head. And p1->next and head->next are also at the same memory location (after we say p1=head), and so are the other next pointers. So, why does setting p1 to nullpointer (or any other value) does not effect head. But, setting p1->next to nullptr, effect head? If you could answer me with a boxed diagram for how the memory is working here, it will be helpful. Thanks!
Upvotes: 1
Views: 111
Reputation: 118340
You are misinterpreting what you're seeing in your debugger. head
is unaffected.
The only thing that head
is, by itself, is the memory address. Nothing more, nothing else.
In your second example, head
must've been 0x007ce390
before p1->next=nullptr
, and it is still the same exact memory address after is assignment.
What your debugger is helpfully showing you is not just the pointer itself, the actual memory address it's pointing to, but also what are all the values the pointer references. Since p1
and head
are now the same pointer, setting p1->next=nullptr
also changes the values that head
points to, and your debugger shows that.
But the pointer itself is unchanged.
Upvotes: 1