1

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; 
2
  • The code you’ve posted isn’t valid C (but it is valid C++). Are you maybe using C++ instead of C? Commented Apr 28, 2020 at 12:53
  • I guess node is pointer to Node structure, i.e. Node * node; Commented Apr 28, 2020 at 13:25

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
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:

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.