Question: What is Pointer to Pointer in C Programming?
Answer: A pointer is a variable that holds address, address of a variable of any basic types, address of a structure, address of an array or address of some other pointer variable. For example,
int val = 10; int *pi = &val; /* pi is a pointer pointing to integer val */ int **ppi = π /* ppi is a pointer to pointer to int */
Can you figure out results of following statements?
val; *pi; **ppi;
val is simplest gives value 10. What about value of *pi? We initialized pi address of integer val. Therefore, pi is pointing to val and we know that indirection on a pointer to something is that thing.
*pi;
results 10. Similarly, ppi is pointing to pi, single indirection on ppi, i.e.
*ppi;
results pi which is pointer to val. Therefore, double indirection on ppi, i.e.
**ppi;
or equivalently,
*(*ppi);
or equivalently,
*(pi);
which is *pi; and this results 10.
Why do we ever need a pointer to pointer when simple assignment works? Actually, consider the instance of insertion of new value in the singly linked list, fragment of code I’ve written below for easy understanding,
/* let's insert new value in the ordered list */ void insert_value(Node **linkp, int new_value) { Node *new_node; Node *current; /* * walk down the list to find appropriate place to insert * the new value */ while ((current = *linkp) != NULL && current->data < new_value) linkp = ¤t->link; /* Let's allocate new node dynamically */ new_node = (Node *)malloc(sizeof(Node)); /* Let's confirm if new_node allocated successfully */ if (new_node == NULL) { puts("ERROR: new_node allocation!"); exit(2); } /* write-in new_value into value field of new_node */ new_node->data = new_value; /* Let's insert new_node into the list */ new_node->link = current; /* new_node points to current node */ *linkp = new_node; /* previous node points to new_node */ puts("**New value successfully added into the list!**\n"); }
Notice here that a simple variable is not known within the function scope and linkp which is pointer to pointer to type Node makes insertion easy and efficient.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
If you wish to look at all C Tutorials, go to C Tutorials.
- Watch Advanced C Programming Videos
- Check C Books
- Apply for Computer Science Internship
- Check Computer Science Books
- Practice BCA MCQs