Double Pointers

Double Pointer References in C when using linked lists


void Push(struct node** headRef, int data) {
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto

Why we need a pointer to node pointer? (struct node** headRef).

Many list functions need to change the caller's head pointer. To do this in the C language,
pass a pointer to the head pointer. Such a pointer to a pointer is sometimes called a
"reference pointer". The main steps for this technique are…
• Design the function to take a pointer to the head pointer. This is the
standard technique in C — pass a pointer to the "value of interest" that
needs to be changed. To change a struct node*, pass a struct
• Use '&' in the caller to compute and pass a pointer to the value of interest.
• Use '*' on the parameter in the callee function to access and change the
value of interest.


Further details (excellent descriptions)@:

Double pointer (**) parameters are common in linked list or

other pointer manipulating code were the value of interest to share and change is itself a
pointer, such as a linked list head pointer.


Reference Parameters in C

Reference Parameters In C
We are bumping into a basic "feature" of the C language that changes to local parameters
are never reflected back in the caller's memory. This is a traditional tricky area of C
programming. We will present the traditional "reference parameter" solution to this
problem, but you may want to consult another C resource for further information. (See
Pointers and Memory ( for a detailed explanation of
reference parameters in C and C++.)
We need Push() to be able to change some of the caller's memory — namely the head
variable. The traditional method to allow a function to change its caller's memory is to
pass a pointer to the caller's memory instead of a copy. So in C, to change an int in the
caller, pass a int* instead. To change a struct fraction, pass a struct
fraction* intead. To change an X, pass an X*. So in this case, the value we want to
change is struct node*, so we pass a struct node** instead. The two stars
() are a little scary, but really it's just a straight application of the rule. It just happens
that the value we want to change already has one star (*), so the parameter to change it
has two (
). Or put another way: the type of the head pointer is "pointer to a struct
node." In order to change that pointer, we need to pass a pointer to it, which will be a
"pointer to a pointer to a struct node".

More @

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License