Tuesday 3 September 2019

c - Why use double pointer when inserting node to the head (linkedlist)?

int list_insert_head(node **phead, int data){
node *newnode = malloc(sizeof(node));
if(newnode == 0)
return 0; /*memory allocation failed*/
newnode -> data = data;
newnode -> next = *phead;
*phead = newnode; /* what is this?*/
return 1;
}

So I'm not quite sure why you have to pass in double pointer **phead,
and only use a single pointer *phead inside the function.
I assume you use double pointer b/c you're manipulating actual head, which itself is a single pointer.
Inside the function by the way, if you were going to do this,


*phead = newnode;

why don't you just pass in *phead in the function parameter?


Thank you.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...