Oct 5, 2014

C Programming #50: Double pointer - inception

Double pointer is like inception. It is like dream within dream.

Just review following article before you start reading this article

1. C Programming #04: Datatypes and Variable
2. C Programming #41: Pointer - introduction

We know that pointer is type of variable that will store the address. Even pointer, is variable and it is also stored in some memory. Extending the concept address of pointer could be stored in special variable called as double pointer.

Let me explain how double pointer is used.

#include <stdio.h>
int main()
   int a = 10,*pa,**ppa;

   /* pa is a pointer pointing to a */
   pa = &a;

   /* ppa is a pointer pointing to pa */
   /* ppa is a double pointer, pointing to a */
   ppa = &pa;

   printf("Value of a is %d, Address of a is %p\n", a, &a);
   printf("Value of pa is %p, Address of pa is %p\n", pa, &pa);
   printf("Value of ppa is %p Address of ppa is %p\n", ppa, &ppa);

   printf("Value of a %d via pa %d via ppa %d\n", a, *pa, **ppa);

   *pa = 20; 
   printf("Value of a is %d\n", a);

   **ppa = 30; 
   printf("Value of a is %d\n", a);

   return 0;
Output of the above program is 

Value of a is 10, Address of a is 0xbfe3b804
Value of pa is 0xbfe3b804, Address of pa is 0xbfe3b808
Value of ppa is 0xbfe3b808 Address of ppa is 0xbfe3b80c
Value of a 10 via pa 10 via ppa 10
Value of a is 20
Value of a is 30

Here is memory layout of the variable.
Lesson learn't from the above program.

  1. Pointer store the address of a variable.
    1. pa = &a; 
  2. Double pointer store the address of the pointer.
    1. ppa = &pa;
  3. Deference operator operator is used once on single pointer.
    1. *pa = 20;
  4. Deference operator operator is used twice on double pointer. 
    1. **ppa = 30;
  5. Note that pa and *ppa are single pointer.
  6. Even double pointer has type attached to it.

In same way it could be extended to triple pointer so on.
But my rule of thumb is that never use triple pointer and high. It is too confusing to even make some meaning.


Next Article - C Programming #51: Void pointer
Previous Article - C Programming #49: Pointer to array
All Article - C Programming

No comments :

Post a Comment