Previous: 6.2 Passing Pointers to Functions
Up: 6.2 Passing Pointers to Functions
Next: 6.2.2 Computing the Square and Cube
Previous Page: 6.2 Passing Pointers to Functions
Next Page: 6.2.2 Computing the Square and Cube

6.2.1 Indirectly Incrementing a Variable

We will first write a program which uses a function to increment the value of an object defined in main(). As explained above, the called function must indirectly access the object defined in main(), i.e. it must use a pointer to access the desired object. Therefore, the calling function must pass an argument which is a pointer to the object which the called function can indirectly access.

Figure 6.11 shows the code for the program and the program trace is shown graphically in Figure 6.12. The function, main() declares a single integer variable and initializes it to 7 (see Figure 6.12a)). When main() calls indirect_incr(), it passes the pointer, &x (the address of x). The formal parameter, p, is defined in indirect_incr() as a pointer variable of type int *. When indirect_incr() is called, the variable, p gets the value of a pointer the the cell named x in main() (see Figure 6.12b)). The function, indirect_incr(), indirectly accesses the object pointed to by p, i.e. the int object, x, defined in main(). The assignment statement indirectly accesses the value, 7, in this cell, and increments it to 8, storing it indirectly in the cell, x, in main() (see Figure 6.12c)).

Sample Session:



Previous: 6.2 Passing Pointers to Functions
Up: 6.2 Passing Pointers to Functions
Next: 6.2.2 Computing the Square and Cube
Previous Page: 6.2 Passing Pointers to Functions
Next Page: 6.2.2 Computing the Square and Cube

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:45:54 HST 1994