next up previous contents
Next: 8.4 Passing Pointers as Up: 8 Arrays and Pointers Previous: 8.2 Passing Arrays as

8.3 Declaring Pointer Variables

Pointers can be passed to functions which then go on to modify the value of the variable being pointed to. This is useful because the same function can be called to modify different variables, just by giving it a different pointer.

Pointers are declared with the use of the asterisk ( *). In the example

    int *foo;
    float *bar;

foo is declared as a pointer to an integer, and bar is declared as a pointer to a floating point number.

To make a pointer variable point at some other variable, the ampersand operator is used. The ampersand operator returns the address of a variable's value; that is, the place in memory where the variable's value is stored. Thus:

    int *foo;
    int x= 5;

    foo= &x;

makes the pointer foo ``point at'' the value of x (which happens to be 5).

This pointer can now be used to retrieve the value of x using the asterisk operator. This process is called de-referencing. The pointer, or reference to a value, is used to fetch the value being pointed at. Thus:

    int y;

    y= *foo;

sets y equal to the value pointed at by foo. In the previous example, foo was set to point at x, which had the value 5. Thus, the result of dereferencing foo yields 5, and y will be set to 5.

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