Pointer to a pointer (Double Pointer) in C

Pointers are used to store the address of other variables of similar datatype. But if you want to store the address of a pointer variable, then you again need a pointer to store it. Thus, when one pointer variable stores the address of another pointer variable, it is known as Pointer to Pointer variable or Double Pointer.

[ Pointer2(address of the pointer1) –> Pointer1(address of the variable) –> Variable(value) ]

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the declaration int **var; declares a pointer to a pointer of type int.

Example

/* C program for Pointer to a pointer */
/* www.codewindow.in

#include <stdio.h>
 
int main () {
	
	int  var;
   	int  *p1;
	int  **p2;
	var = 10;
	p1 = &var;	 // take the address of var 
	p2 = &p1;	// take the address of p1 using address of operator &

   	printf("Value of var = %d\n", var );
   	printf("Value available at *p1 = %d\n", *p1 );
   	printf("Value available at **p2 = %d\n", **p2);
   	printf("Value at the address stored by p2 = %u\n", *p2);

   	return 0;
}

Output:
Value of var = 10
Value available at *p1 = 10
Value available at **p2 = 10
Value at the address stored by p2 = 2456761

Explanation:
1. p1 pointer variable can only hold the address of the variable var. Similarly, p2 variable can only hold the address of variable p1. It cannot hold the address of variable var.

2. *p2 gives us the value at an address stored by the p2 pointer. p2 stores the address of p1 pointer and value atthe address of p1 is the address of variable var. Thus, *p2 prints address of var.

3. **p2 can be read as *(*p2). Hence, it gives us the value stored at the address *p2. From above statement, you know *p2 means the address of variable a. Hence, the value at the address *p2 is 10. Thus, **p2 prints 10.


You Missed

Also Checkout