Originally Posted by
seal308
I always thought that if you have a pointer in a struct you have to malloc that pointer before you can set it to something.
You only need to be sure you point to valid memory. If an object already exists, you can point to it just fine. If not, then you need to allocate memory for a new object.
Originally Posted by
seal308
When addCell gets called again top is not NULL there is stuff in it, so don't you have to allocate space for it first before you can set it to something?
Have you tried tracing it through by hand (on paper)? It appears to work out just fine.
The first time, memory is allocated for a node, and its "next" pointer is set to "top", which is NULL.
Code:
.
CellNode
+----------+
| |
| (cell 1) |
| | (top)
| (next)--|---> NULL
| |
+----------+
Then "top" is updated with the address of this new cell. So now, it looks like this:
Code:
.
Top
+----------+
| |
| (cell 1) |
| |
| (next)--|---> NULL
| |
+----------+
The next time through, it creates a new node, and its "next" pointer is set to "top":
Code:
.
CellNode Top
+----------+ +----------+
| | | |
| (cell 2) | | (cell 1) |
| | | |
| (next)--|--->| (next)--|---> NULL
| | | |
+----------+ +----------+
Once again, "top" is updated with the address of the new cell:
Code:
.
Top
+----------+ +----------+
| | | |
| (cell 2) | | (cell 1) |
| | | |
| (next)--|--->| (next)--|---> NULL
| | | |
+----------+ +----------+
So it appears to be building the list backwards.
Originally Posted by
seal308
But my teacher posted sample code of:
Tell your teacher they should not be casting the return value of "malloc()": FAQ > Casting malloc - Cprogramming.com