Reputation: 29
What is the difference between these two lines of C code?
node = node->next;
*node = *(node->next);
node
is a linked list Node struct which is defined as following:
struct Node{
int data;
Node* next;
};
Node* node;
Upvotes: 1
Views: 1165
Reputation: 3699
node = node->next;
You assign pointer to pointer.
*node = *(node->next);
It's dereference of pointer. It assigns value of node
to value of next node node->next
.
Look at the picture below:
Upvotes: 1
Reputation: 51835
The first code snippet, node = node->next;
, is a pointer assignment. That is, the address value that is currently in node
will be replaced with the address that is in node->next
.
The second snippet, *node = *(node->next);
, dereferences the pointers, and copies the actual data of the structure that the RHS points to into the structure that the LHS points to. This will be equivalent to the following:
node->data = node->next->data;
node->next = node->next->next;
Note: In this second case, the address that node
contains does not change; that is, it still points to the same location in memory, but the contents of that memory will be changed. In the first case, node
will point to a different (probably) memory location, and the contents of the old location will be left untouched.
Upvotes: 6
Reputation: 2558
pointer vs values. The first one you assign the node
pointer to the pointer at node->next
. The second one you dereference the value of *(node->next)
, meaning you take its value, and assign it to the value at node.
Upvotes: 1