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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With