Multiple Indirection. McGraw-Hill The Complete Reference Fourth Edition
Reklaam
Reklaam
C h a p t e r 5 : P o i n t e r s
123
Remember, q is not a pointer to integers, but rather a pointer to an array of pointers to integers. Therefore you need to declare the parameter q as an array of integer pointers, as just shown. You cannot declare q simply as an integer pointer because that is not what it is.
Pointer arrays are often used to hold pointers to strings. You can create a function that outputs an error message given its code number, as shown here: void syntax_error(int num)
{ static char *err[] = {
"Cannot Open File\n",
"Read Error\n",
"Write Error\n",
};
"Media Failure\n"
} printf("%s", err[num]);
The array err holds pointers to each string. As you can see, printf( ) inside
syntax_error( )
is called with a character pointer that points to one of the various error messages indexed by the error number passed to the function. For example, if num is passed a 2, the message Write Error is displayed.
As a point of interest, note that the command line argument argv is an array of character pointers. (See Chapter 6.)
Multiple Indirection
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.
124
C + + : T h e C o m p l e t e R e f e r e n c e
Figure 5-3.
Single and multiple indirection
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.
Laadi alla
Reklaam