Sunday, September 26, 2010

Multiple Indirection of Pointers C,C++

You can have a pointer point to another pointer that points to the target value. This
situation is called multiple indirection, or pointers to pointers. Pointers to pointers can
be confusing. Figure 5-3 helps clarify the concept of multiple indirection. As you can
see, the value of a normal pointer is the address of the object that contains the value
desired. In the case of a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the object that contains the value desired.
Multiple indirection can be carried on to whatever extent rquired, but more than a
pointer to a pointer is rarely needed. In fact, excessive indirection is difficult to follow
and prone to conceptual errors.
Do not confuse multiple indirection with high-level data structures, such as linked
lists, that use pointers. These are two fundamentally different concepts.
A variable that is a pointer to a pointer must be declared as such. You do this by
placing an additional asterisk in front of the variable name. For example, the following
declaration tells the compiler that newbalance is a pointer to a pointer of type float:
float **newbalance;
You should understand that newbalance is not a pointer to a floating-point number
but rather a pointer to a float pointer.
To access the target value indirectly pointed to by a pointer to a pointer, you must
apply the asterisk operator twice, as in this example:
#include <stdio.h>
int main(void)
{
int x, *p, **q;
x = 10;
p = &x;
q = &p;
printf("%d", **q); /* print the value of x */
return 0;
}
Here, p is declared as a pointer to an integer and q as a pointer to a pointer to an
integer. The call to printf() prints the number 10 on the screen.

No comments:

Post a Comment