I was reading Skeina's book. I could not understand this code. Basically what is the use of double pointer. And what is the use of *l = p
? Can anyone please explain by diagram.
void insert_list(list **l, item_type x) {
list *p; /* temporary pointer */
p = malloc(sizeof(list));
p->item = x;
p->next = *l;
*l = p;
}
You shouldn't call it a "double pointer" because that would be a pointer to a
double
. It is a pointer to a pointer, and it is used to allow the function to alter the value of an argument which happens to be a pointer. If you're familiar with C#, it's like anout
argument. In this situation thel
argument used to get both IN and OUT behavior, but you may often see this used for output only.Since this function returns type
void
it very well could have been written without the use of the pointer to a pointer like this:This change would require the code that calls the function to update it's own handle to the list since the head of the list is what's being changed.