Reputation: 753
I have a pointer to a node in a linked list:
struct node *temp = head.next
If I set this pointer equals to NULL
such as:
temp = NULL;
will this also affect the node I was pointing to? i.e. head.next
is now NULL
?
Upvotes: 4
Views: 1847
Reputation: 213882
There is nothing magical or special with pointers, they follow the same rules as any other variable type.
Consider:
int x = 5;
int y = x;
y = 0;
The y = 0;
will of course not change the value of x
. The very same applies to your example.
I think you are somehow confusing this with changing the contents of a pointed-to variable. If you would instead do
int x = 5;
int* y = &x;
*y = 0;
Then *y = 0;
would change x
. But y
would remain unchanged - it is still pointing at x
Upvotes: 1
Reputation: 1513
No, because you didn't change the content of the pointer.
You just told him to point on something else.
Upvotes: 4
Reputation: 910
All of the above answers are very well explained but may be confusing to people who have just started learning pointers.
Both temp
and head.next
are variables of type struct node *
. Just forget pointers for a second and think about your question if both of struct node *
variables where just int
.
See this analogy:
int a = 1;
int b = a;
b = 0;
// a remains 1, b is 0
Now back to your question:
struct node* head.next = 1; // Some initial value
struct node* temp = head.next; // temp now has the value of 1
temp = NULL; // temp assigned the value of NULL, variable head.next remains unchanged
Upvotes: 3
Reputation: 3215
No it will not. You have to understand the when you update a pointer you don't update its content or the memory location it was pointing to. For that you have to explicitly do it.
Now for your problem:
temp
is holding an address of memory location where head->next resides. Something like (0x980901) setting it to null will only change the address it was pointing ie. now it will point to nothing.
Let me explain this to you using an anology. Suppose you have a piece of paper and upon it you have written address of your friends house. You erase the content written on this piece of paper does that mean you friend was moved out of his house? Obviously not.
In your case this piece of paper is temp pointer.
Upvotes: 6
Reputation: 12270
will this also affect the node I was pointing to? i.e. head.next is now NULL?
No.
head.next
is a variable holding a value (address). When you do
struct node *temp = head.next
Now temp
also has the same value as head.next
.
Later when you change the value of temp
, why should the value held by head.next
change.
This is the difference when you copy the value of a variable (which is happening is this case), and when you make a variable refer to some other variable, and change its content.
If you want the latter then you need a pointer to pointer to struct node
Something like
struct node **temp = &head.next;
Now if you want to change the content of head.next
also through temp
you can do by
*temp = NULL;
Upvotes: 9