Pointers may also represent the concept of multiple
indirection (see Section 5.2). The rule to derive
from a type T a type “pointer to T” can be applied to this last
type to obtain a “pointer to pointer to T” defined as
“T **
”.
These multiple pointers have the same than a regular pointer, the difference is only in the number of indirections to obtain the data. The following program is an example in which pointers with several indirection levels are manipulated:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> int main() { int i; int *ptrToi; /* Pointer to integer */ int **ptrToPtrToi; /* Pointer to pointer to integer */ ptrToPtrToi = &ptrToi; /* Pointer contains address of pointer */ ptrToi = &i; /* Pointer contains address of integer */ i = 10; /* Direct assignment */ *ptrToi = 20; /* Indirect assignment */ **ptrToPtrToi = 30; /* Assignment with double indirection */ return 0; } |
The following figure shows the evolution of the value of all
variables during the code execution. Note that even though there is no
value assigned to variable i
, the address of any variable can
be obtained and stored without any problem.
Copy and paste the content of the previous program in a
text file in your development environment. Use the instruction
“printf("%d\n", x);
” to print the integer
referred by “x
”. Modify the assignments and
print the variables to show how the indirection is performed.