Site hosted by Angelfire.com: Build your free website today!



Next: Arrays and Pointers Up: Functions in C Previous: Modifying Function Arguments

Pointers in C

Pointers are not exclusive to functions, but this seems a good place to introduce the pointer type.

Imagine that we have an int called i. Its address could be represented by the symbol &i. If the pointer is to be stored as a variable, it should be stored like this.


int *pi = &i;
int * is the notation for a pointer to an int. & is that operator which returns the address of its argument.

The opposite operator, which gives the value at the end of the pointer is *. An example of use would be


i = *pi;
This is known as de-referencing a pointer.

Be careful not to confuse the many uses of the * sign; Multiplication, pointer declaration and pointer de-referencing.

This is a very confusing subject, so let us illustrate it with an example. The following function swap exchanges the values of its two arguments. The arguments are passed as pointers so that their values can be modified in the calling function.


swap(i, j)
int *i, *j;
{       int temp;

        temp = *i;
        *i = *j;
        *j = temp;
}

i and j are declared as pointers to int. The local variable temp is an int. The lines in the body of the function exchange the values referenced by i and j.

Note that i and j are not swapped directly. Instead they are de-referenced, and the integers which they point to are swapped.

A very simple program to use this function might appear as follows.


main()
{       int i = 0;
        int j = 1;

        printf("I is %d and J is %d\n", i, j);
        printf("Swapping the values now\n");
        swap(&i, &j);
        printf("I is %d and J is %d\n", i, j);
}
Note here how pointers to int are created using the & operator in the same line as the function call swap(&i, &j);

To summarise, if you wish to use arguments to modify the value of variables from a function, these arguments must be passed as pointers, and de-referenced within the function.

Of course, where the value of an argument isn't modified, the value can be passed without any worries about pointers.



Next: Arrays and Pointers Up: Functions in C Previous: Modifying Function Arguments