Friday, November 5, 2010

Pointer to pointer in C programming language


The concept of pointer can be extended further. Pointer can hold the address of another variable. But what will happen if the variable itself is a pointer. The address of a pointer can be stored on a variable which is called pointer to pointer.

#include< stdio.h >
void main()
{
 int i,*j,**k;
 /* here j is a pointer and k is pointer to pointer*/
 i=5;
 j=&i;
 k=&j;
  printf("\nAddress of 'i'=%u",&i);
  printf("\nAddress of 'i'(displayed through 'j')=%u",j);
  printf("\nAddress of 'i'(displayed through 'k')=%u",*k);
  printf("\nAddress of 'j'=%u",&j);
  printf("\nAddress of 'j'(displayed through 'k')=%u",k);
  printf("\nAddress of 'k'=%u",&k);
  printf("\nNow the values...\n");
  printf("\nValue of 'j'( this will be the address of 'i')=%u",j);
  printf("\nValue of 'k' (this will be the address of 'j')=%u",k);
  printf("\nValue of 'i' displayed through 'j'=%d",*j);
  printf("\nValue of 'i' displayed through 'k'=%d",**k);
 }

A chart will demonstrate this feature
Location
 Name       i          j          k
Value      5       1002     1000       
Address 1002  1000      998

Difference between *ptr++ and ++*ptr  (assume ptr is a pointer and pointing to some location)
*ptr++ statement increments the pointer means the pointer moves to the next location while ++*ptr statement increments the value of the location pointed by the pointer by 1.
++*ptr statement can be also written as (*ptr)++

Another example using C Language

#include< stdio.h >
void main()
{
 int x,*y;
 void *z;
 x=10;
 z=&x;
 y=(int *)z;
printf("\nAddress of 'x'=%u",&x);
printf("\nAddress of 'x'through 'y'=%u",y);
printf("\nAddress of 'x' through 'z'=%u",z);
}
 all the three statements will generate the same output, address of the variable ‘x’


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner