Thursday, 19 January 2012

Program Of Pointer To Pointer In C++


#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
int a,*b,**c;
a=10;
b=&a;
c=&b;
cout<<"\n Value of a="<<a;
cout<<"\n Value of b="<<b;
cout<<"\n Value of c="<<c;
cout<<"\n Value of c="<<*c;
cout<<"\n Value of c="<<**c;
getch();
}

------------------------------------------------------------------------------

Since we can have pointers to int, and pointers to char, and pointers to any structures we've defined, and in fact pointers to any type in C, it shouldn't come as too much of a surprise that we can have pointers to other pointers. If we're used to thinking about simple pointers, and to keeping clear in our minds the distinction between the pointer itself and what it points to, we should be able to think about pointers to pointers, too, although we'll now have to distinguish between the pointer, what it points to, and what the pointer that it points to points to. (And, of course, we might also end up with pointers to pointers to pointers, or pointers to pointers to pointers to pointers, although these rapidly become too esoteric to have any practical use.)
The declaration of a pointer-to-pointer looks like
 int **ipp;
where the two asterisks indicate that two levels of pointers are involved.
Starting off with the familiar, uninspiring, kindergarten-style examples, we can demonstrate the use of ipp by declaring some pointers for it to point to and some ints for those pointers to point to:
 int i = 5, j = 6; k = 7;
 int *ip1 = &i, *ip2 = &j;
Now we can set
ipp = &ip1;
and ipp points to ip1 which points to i*ipp is ip1, and **ipp is i, or 5. We can illustrate the situation, with our familiar box-and-arrow notation, like this: 


If we say
*ipp = ip2;
we've changed the pointer pointed to by ipp (that is, ip1) to contain a copy of ip2, so that it (ip1) now points at j

If we say
*ipp = &k;
we've changed the pointer pointed to by ipp (that is, ip1 again) to point to k
What are pointers to pointers good for, in practice? One use is returning pointers from functions, via pointer arguments rather than as the formal return value. To explain this, let's first step back and consider the case of returning a simple type, such as int, from a function via a pointer argument. If we write the function
 f(int *ip)
 {
  *ip = 5;
 }
and then call it like this:
int i;
 f(&i);
then f will ``return'' the value 5 by writing it to the location specified by the pointer passed by the caller; in this case, to the caller's variable i. A function might ``return'' values in this way if it had multiple things to return, since a function can only have one formal return value (that is, it can only return one value via the return statement.) The important thing to notice is that for the function to return a value of type int, it used a parameter of type pointer-to-int.


view source:-  http://www.eskimo.com/~scs/cclass/int/sx8.html

No comments:

Post a Comment