I am trying to understand the pointer logic behind prepending.
I declared a struct as follows:
typedef struct myList{
int info;
struct myList *link; //self referential structure;
} Node;
For memory allocation in the heap memory segment, I use the following function:
Node *getNode(){
return ((Node *)malloc(sizeof(Node)));
}
In the main function, I allocate memory for the first node, I assign its link to NULL and its value to 2.
Node *head = getNode();
head -> link = NULL;
head -> info = 2;
Then comes the prepend function:
void prepend(Node **headPointer, int value) {
Node *new_node;
new_node = getNode();
new_node -> info = value;
new_node -> link = *headPointer;
*headPointer = new_node;
}
I am using the following function call:
prepend(&head, 5)
As you can see, I'm using a pointer to a pointer. I store the address of head in headPointer. I create new_node and allocate memory to it. I assign its info field, then the link field gets the dereferenced headPointer, which is the value stored in head, which is in turn the address for the chunk of memory in the Heap segment.
So, I basically link new_node to head, right? Now comes the confusing part, for me. The dereferenced headPointer, which is head's pointed chunk of memory in the Heap segment, gets the value stored in new_node which is another address from the Heap segment, I guess. Then, both new_node and headPointer go out of scope. (?)
How does this all add up? Is there a simpler way to describe the situation or implement prepending?