Tuesday, September 3, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...