Pointer to Pointer in C
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Typically, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value.
A variable that is a pointer to a pointer must be declared as such, which means placing two asterisks in front of the variable name. For example, the following declares a pointer to a pointer to an int
:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing this value requires the use of two asterisk operators, as shown in the following example:
Example
#include <stdio.h>
int main ()
{
int V;
int *Pt1;
int **Pt2;
V = 100;
/* Get the address of V */
Pt1 = &V;
/* Get the address of Pt1 using the & operator */
Pt2 = &Pt1;
/* Access the value using pptr */
printf("var = %d\n", V );
printf("Pt1 = %p\n", Pt1 );
printf("*Pt1 = %d\n", *Pt1 );
printf("Pt2 = %p\n", Pt2 );
printf("**Pt2 = %d\n", **Pt2);
return 0;
}
When the above code is compiled and executed, it produces the following result:
var = 100
Pt1 = 0x7ffee2d5e8d8
*Pt1 = 100
Pt2 = 0x7ffee2d5e8d0
**Pt2 = 100