What happens after a function call when you have a pointer from one pointer struct point to another struct that has allocated memory? I asked a question earlier about structs that lead me to asking this question: scope of struct pointers in functions
For example:
struct example{
//variables and pointers
struct clip *next;
}*Head
and then i have a pointer of datatype struct in a function:
struct example *newNode=malloc(sizeof(struct example));
And in the same function i link the first node(the head) to the second node(the new node):
Head->next=newNode;
Does the linking/pointing still hold after the function exits? I'm not sure if that makes sense but when you add a new node at the end of your linkedlist you have to go through the linkedlist in the first place to see where it ends(next pointer = NULL).
For example:
void insert_at_end(){
//We have a pointer cp that goes through the linked list, initially cp->next points to `null so we create a newnode right away`
//struct example cp and newnode gets malloc'd here
if(Head != NULL){
cp=Head;
while(cp->next !=NULL){
cp=cp->next;
}
cp->next=newNode;
else{
//We link the head to the newNode `because we don't want to change the head for each new node added.`
head=newNode;
}
}
but after each newNode added at the end of the list we exit the function so what happens when we re-enter the function and go through the linkedlist to see where it ended? How does it know what cp->next points to?
gcc -Wall -g
on Linux), and step by step with the debugger (gdb
on Linux), displaying the relevant pointers, to find out. Write on a chalkboard what is happening. Read several good C programming books. You need to understand what the heap is, and whatmalloc
andfree
are doing. – Basile Starynkevitch