14K
14K

Reputation: 439

Equal sign when implementing a linked list

What is the meaning of "=" when you try to switch a pointer.

for example: current->next = previous and current = previous.

Upvotes: 1

Views: 102

Answers (1)

NicholasM
NicholasM

Reputation: 4673

Let's take the second assignment, current = previous. Here, the small boxes are the values of the pointers themselves, while the rectangles on the right are the things they point to.

Before assignment:

         +---+          +-----------+
current  | --|--------> | Obj1      |
         +---+          +-----------+

         +---+          +-----------+
previous | --|--------> | Obj2      |
         +---+          +-----------+

After assignment, both current and previous point to the object Obj2.

         +---+          +-----------+
current  | --|--+       | Obj1      |
         +---+  |       +-----------+
                |
         +---+  +-----> +-----------+
previous | --|--------> | Obj2      |
         +---+          +-----------+

Important takeaways:

  • For an ordinary, raw pointer, the original Obj1 that current used to point to is unchanged. It is not "deleted" or destructed by virtue of the assignment.
  • Indeed, the assignment modifies neither Obj1 nor Obj2 themselves.
  • If you change Obj2 (say, using *current = func()), then its changed state will be reflected when you access (read) it through either current or previous.
  • It is very important to remember that pointers store memory addresses, and memory addresses are just numbers. So, when you assign a pointer to another, you're just putting a new number (i.e. address) in there.

Upvotes: 4

Related Questions