Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does insertion into a list require a pointer to a pointer

Tags:

c

pointers

The textbook describes the insertion algorithm this way, my question is, can't it be accomplished by the second function, shown below which doesn't include a pointer to a pointer, instead working with *l and l.

void insert (list **l, int d)
{
    list *p; 

    p = malloc(sizeof(list)); 
    p.data = x;
    p.next = *l; 
    *l = p;
}


void insert1 (list *l, int d){
    list *p;
    p = malloc(sizeof(list));
    p.data = x;
    p.next = l;
    l = p; 
}
like image 875
drewyu Avatar asked Dec 14 '22 16:12

drewyu


1 Answers

Everything is passed by value in C. This includes your pointer. So, when you say l = p; at the end of your function, this is without effect on the caller of insert1(). You are just modifying a local variable of insert1() (that happens to hold a pointer).

However, when you say *l = p; at the end of insert(), you are writing the pointer to a memory location that's controlled by the caller. The caller typically does something similar to this:

list* myList = ...;
insert(&myList, ...);

With this, the *l = p; directly modifies the value of myList in the caller, allowing the caller to actually see an effect.

like image 140
cmaster - reinstate monica Avatar answered Mar 04 '23 00:03

cmaster - reinstate monica