What's the Point

Before looking deeper into what pointers are all about, an example would be helpful. Consider the problem of writing a function that swaps two integers. Say for example, we want to sort an array of integers (put them in order). Part of sorting involves swapping elements in the array. Now a function can return a single integer, but not the two changed ones. Also if we try to write swap like:

void swap( int x, int y )
   int temp ;

   temp = x ;
   x = y ;
   y = temp ;

we'd have a problem. We would indeed swap the values of x and y, but they are only local copies of the numbers. If we call swap() with a command like:

swap( a[i], a[j] ) ;

then the values of a[i] and a[j] won't be changed.

However, we can write swap() using pointers. Consider the function:

void swap( int *x, int *y )
   int temp ;

   temp = *x ;
   *x = *y ;
   *y = temp ;

Here we're not swapping the values of x and y. They are pointers to the actual numbers we want to swap, so we swap the integers that they point to. That also means that we call it differently; we would call swap() with a statement like:

swap( &a[i], &a[j] ) ;

This figure shows the situation before calling swap(),

[Pointers before calling swap()]

and this figure shows the situation at the end of swap().

[Pointers after calling swap()]

Proceed to the next part.