drewyu
drewyu

Reputation: 105

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

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; 
}

Upvotes: 4

Views: 95

Answers (3)

Achal
Achal

Reputation: 11921

Why does insertion into a list require a pointer to a pointer ? it's because if you do that modification in *l will affect in calling function also & that's what our intention if you want to link nodes. This *l = p; in below code will modify the head node in the calling function probably main().

void insert (list **l, int x) { /*. .. */ }

If you pass only pointer as you did in second code *l doesn't get modified in calling function. This l = p; doesn't change head node in calling function.

Upvotes: 3

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.

Upvotes: 5

javidcf
javidcf

Reputation: 59711

No, you can't. The problem with insert1 is in the following line:

l = p;

This will set the value of l to p, but l is only a function-local variable holding the value of the pointer to the list. Changing l here will not have any effect outside of the function. So if I have a code like:

list *myList = /* ... */;
insert1(myList, 0);

The pointer myList here will not be changed. On the other hand, with the code:

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

The pointer myList will be updated to point to the newly inserted value.

Upvotes: 4

Related Questions