Figure 8.7 passes the variable number
to function cubeByReference
using pass-by-reference with a pointer argument (line 15)—the address of number
is passed to the function. Function cubeByReference
(lines 21–24) specifies parameter nPtr
(a pointer to int
) to receive its argument. The function uses the dereferenced pointer to cube the value to which nPtr
points (line 23). This directly changes the value of number
in main
(line 11). Line 23 is equivalent to
*nPtr = (*nPtr) * (*nPtr) * (*nPtr); // cube *nPtr
A function receiving an address as an argument must define a pointer parameter to receive the address. For example, the header for function cubeByReference
(line 21) specifies that cubeByReference
receives the address of an int
variable (i.e., a pointer to an int
) as an argument, stores the address in nPtr
and does not return a value.
Function cubeByReference
’s prototype (line 7) contains int *
in parentheses. As with other types, it isn’t necessary to include the names of pointer parameters in prototypes. Parameter names included for documentation purposes are ignored by the compiler.
18.218.97.75