Pointers - 13 Pointer to Pointer

Pointer to Pointer

   A pointer to pointer is a kind of chain of pointer. Usually when the pointer is declared and assigned to a particular variable. Later on we can have a pointer to pointer variable can be declared to hold the address of first pointer. To declare a pointer to pointer we need write an extra asterisk mark(*). Even to access the value of variable one need to write two asterisk mark(*).


     The above diagram shows pointer to pointer representation. In that a memory location whose address is 1001 contains a value 10. A pointer can be used to store the address 1001 into 2002(first pointer). Another pointer can be declared to store the address of 2002 into 4001 memory locations. 

Now we will have an example,

#include

main ()
{
   /* section 1 */
   int  a;
   int  *p1;
   int  **p2;
   /* section 2 */
   a = 10;


   p1 = &a;


   p2 = &p1;

   /* section 3*/
   printf ( " \n Value of a is  %d", a );
   printf ( " \n Address of a is %u ", &a );
   printf ( " \n pointer p1 points to %u ", p1 );
   printf ( " \n pointer p2 points to %u ", p2 );
   printf ( " \n Value of a using pointer to pointer is  %d", **p2);


}
 

In the above program,
section 1 contains the declaration of variable a, pointer variable p1 and pointer to pointer variable p2 observe two ** in declaration.

section 2 contains,
  - value 10 is assigned to variable a.
  - Address of a is assigned to p1.
  - Address of p1 is assigned to pointer to pointer variable p2.

section 3 contains,
  - first printf() prints value of a i.e. 10
  - second printf() prints the address of a i.e. 1001 (with ref. to above diagram)
  - third printf() prints the address present at p1 i.e. nothing but address of a.
  - fourth printf() prints the address present at p2 i.e. address of p.
  - fifth prints () prints the value of a through pointer to pointer p2.

Comments