Let's look at what happens to the memory in your program. You start with 3 local variables, all of type Node*
. At the moment they all point to garbage, as they have been declared but not initialised.
An ascii art diagram of the memory might be (The layout is implementation dependant)
list node tail
--------------------------
... | 0xFE | 0x34 | 0xA3 | ...
--------------------------
You then set list to NULL
, and tail
to the address of node (casting away its type, a bad idea), giving you
list node tail
--------------------------
... | NULL | 0xFE | &list | ...
--------------------------
^ |
+-------------+
You then malloc a new Node
, setting list to its address.
list node tail next value
--------------------------- ------------------
... | NULL | &next | &list | ... | NULL | 100 | ...
--------------------------- ------------------
^ | | ^
| +---------------------+
+--------------+
You next try to set tail->next
to node. You've said that you know tail
points to a Node
when you did the typecast, so the compiler believes you. The Node
tail points to starts at list
's address, like so
tail list
next value next value
---------------------------------- ------------------
... | NULL | &list->next | &list | ... | NULL | 100 | ...
---------------------------------- ------------------
You then set tail->next
to node
, making both list
and node
point to the list
structure.
list node tail next value
--------------------------- ------------------
... | &next | &next | &list | ... | NULL | 100 | ...
--------------------------- ------------------
| ^ | | ^
| | +---------------------|
| +-------------+ |
+-----------------------------+
You've printed list
as a signed integer ("%d"). This is a bad idea - if you are using a 64 bit machine and have other arguments in the printf statement they may be clobbered, use the pointer format ("%p") instead. list->value
is the same as node->value
, so it's still going to be 100
.
Pointers become easier if you think about how they actually are represented in the machine - as an index to a huge array which holds all of your data (modulo pointer sizes, virtual memory etc.).
Next time it might be easier just to use list = node
.