Reputation: 43
I found this linked list routine (from Unix System Programming by Haviland) to add an item to a singly linked list.
additem(item **head, item *newitem)
{
newitem->next = *head;
*head = newitem;
}
My difficulty is in trying to understand the item **head
part. What does the **head
really mean? Why not define the routine with just item *head
as follows:
additem(item *head, item *newitem)
{
newitem->next = head;
head = newitem;
}
Upvotes: 2
Views: 112
Reputation: 4749
http://cslibrary.stanford.edu/102/PointersAndMemory.pdf may be helpful for you to understand.
Upvotes: 1
Reputation: 191
Just understand simply that: if you want another function to change the value of a variable. You have to pass its address since C use "call by value" mechanism.
void change_value(type *a)
{
*a = ...;
}
In this case, you want to change the value of a pointer to head type (head*), so its addr has the type of head**
type * a equal to (head*) *a or head **a
Upvotes: 0
Reputation: 27894
It is a pointer to a pointer.
In C you cannot change variables passed by value, as parameters are handled as local variables. You have to pass their pointers instead, and then modify the value of *variable
.
It also applies when the variable you want to change is already a pointer. In this case you have to pass the pointer to that pointer, so when you change this pointer, this change propagates to the caller.
*head
is the value head
is pointing to. while head
is of type item **
, *head
is of type item *
.
When you do this:
additem(item *head, item *newitem)
{
newitem->next = head;
head = newitem;
}
Modifying the value of head
does not affect it's value to the caller. To all purposes it is meaningless to change head
in this context.
Upvotes: 3
Reputation: 122443
You have the answer of your first question in your title: item **head
means head
is a pointer to a pointer.
Why your second code snippet doesn't work? because
head = newitem;
assigns the value to the local variable head
, which is not what the code is intended to do.
Upvotes: 1
Reputation: 2721
If you just passed the pointer *head
to the child routine and change its value and try to return it, you will discover you cannot because it is a value passed to the routine which only exists on the routine's stack as long as the routine is in scope. However, you can pass a pointer to that pointer (**head
, which will be local on the stack as well), and change the value of what it points to, and then the value you want to be changed in the scope of the calling routine is actually changed.
This is the 'C way' of achieving call-by-reference even though C only officially supports call-by-value — it uses a call-by-value with a value that is a reference to the thing you want to change, thus allowing call-by-reference.
Upvotes: 0