Multiple Indirection Pointers to Pointers

It is possible in C to have a pointer point to another pointer that points to a target value. This is termed multiple indirection in this case double indirection. Multiple indirection can be carried out to whatever extent is desired but can get convoluted if carried to extremes.
In the normal situation, single indirection, a pointer variable would hold the address in memory of an appropriate variable, which could then be accessed indirectly by de-referencing the pointer using the * operator.

In the case of double indirection, we have the situation where a variable may be pointedto by a pointer as with single indirection, but that this pointer may also be pointed to by another pointer. So we have the situation where we must de-reference this latter pointer twice to actually access the variable we are interested in. De-referencing the pointer to a pointer once gives us a normal singly indirected pointer, de-referencing the pointer to a pointer secondly allows us to access the actual data variable.

To declare a pointer to a pointer we include another indirection operator

float * * ptr ;
which in this case defines a pointer to a pointer to type float.
The following illustrates some valid operations using double indirection.
int x = 10, *p, **q ;
p = &x ;
q = &p ;
**q = 20 ; // de-reference twice to access value
p = *q ; // de-reference q once to get a pointer to int

int array1[] = { 1,2,3,4,5,6 ,7 ,8,9,10} ;
int array2[] = {10,20,30,40,50} ;
int *pointers[2] ; // an array of pointers to type int
int **ptr ; // a doubly indirected pointer
ptr = pointers ; // initialise pointer to array of pointers
*ptr++ = array1 ; // now we simply de-reference the pointer to a
pointer
*ptr = array2 ; // once and move it on like any pointer
**ptr = 100 ; // ptr is pointing at pointers[1] which in turn is
pointing
// at array2 so array2[0] is assigned 100
Multiple Indirection Pointers to Pointers Multiple Indirection Pointers to Pointers Reviewed by Unknown on 04:40 Rating: 5

No comments:

Powered by Blogger.