next up previous contents
Next: 9 Library Functions Up: 8 Arrays and Pointers Previous: 8.3 Declaring Pointer Variables

8.4 Passing Pointers as Arguments

Pointers can be passed to functions; then, functions can change the values of the variables that are pointed at. This is termed call-by-reference; the reference, or pointer, to the variable is given to the function that is being called. This is in contrast to call-by-value, the standard way that functions are called, in which the value of a variable is given the to function being called.

The following example defines an average_sensor function which takes a port number and a pointer to an integer variable. The function will average the sensor and store the result in the variable pointed at by result.

In the code, the function argument is specified as a pointer using the asterisk:

    void average_sensor(int port, int *result)
    {
      int sum= 0;
      int i;

      for (i= 0; i< 10; i++) sum += analog(port);

      *result=  sum/10;
    }

Notice that the function itself is declared as a void. It does not need to return anything, because it instead stores its answer in the pointer variable that is passed to it.

The pointer variable is used in the last line of the function. In this statement, the answer sum/10 is stored at the location pointed at by result. Notice that the asterisk is used to get the location pointed by result.



Fred G. Martin
Fri Mar 29 17:44:15 EST 1996