9.11.2012

Pointer Extend Example

Can a pointer variable, itself might be another pointer?
Yes, this pointer would be contains another pointer's address.

The following example/program should should make this point clear:

/*c program for pointer extend example*/

#include<stdio.h>
int main()
{
 int x=5;
 int *y, **z;

 y = &x;
 z = &y;

 printf("\nAddress of x = %u", &x);
 printf("\nAddress of x = %u", y);
 printf("\nAddress of x = %u", *z);
 printf("\nAddress of y = %u", &y);
 printf("\nAddress of y = %u", z);
 printf("\nAddress of z = %u", &z);
 printf("\nValue of y = %u", y);
 printf("\nValue of z = %u", z);
 printf("\nValue of x = %u", x);
 printf("\nValue of x = %u", *(&x));
 printf("\nValue of x = %u", *y);
 printf("\nValue of x = %u", **z);

 getch();
 return 0;
}

The output of the above program would be:


Output of pointer extend example C program
Screen shot for pointer extend example C program


Read above program carefully, the addresses that get output might be something different.
The relationship between x, y and z can be easily summarized as:

Name ----------------       x                    y               z

Value -------------------    5               2293620       2293616

Address ---------------- 2293620        2293616       2293612


What is the meaning of int x, *y, **z;

Here, x is an ordinary int variable,
y is a pointer to an int i.e. integer pointer,
z is pointer to an integer pointer.

We can extend the above program still further by creating a pointer to a pointer to an integer pointer i.e.  ***n
There is no limit on how far can we go on extending this definition. Possibly, till the point we can comprehend it. And that point of comprehension is usually a pointer to a pointer.


Related programs:


  1. What is Pointer?
  2. Concept of Pointer
  3. Pointer basic example

4 comments:

  1. hey sir ,
    in above program why we use int main instead of void main ?

    ReplyDelete
    Replies
    1. @Rajat Singh Rajput,

      You can use void main instead of int main.

      I used int main, so in the end of program i used "return 0", if you use void main then its nothing return.

      There are some IDE(Integrated Development Environment) that's we need to used int main for proper run/output of the program.

      Thanks for comment. Happy Coding.

      Delete
    2. Hey sir ,
      I have one problem please help me
      How to write did program,
      Write to print all prime dates from February 1900.
      Sir. Please solve as soon as possible
      Advance thanks

      Delete