next up previous
Next: Math Functions & Macros Up: intro_C_examples Previous: External Variables and Scope

Pointers

A pointer is a variable that contains the address of a variable. For example:

  int i,j; /* simple integer variables */
  int *pi; /* pointer to an integer variable */

  i = 10;  /* assign the value 10 to i */
  pi = &i; /* assign the address of i to pi */
  j = *pi; /* assign the contents of address pi to j */
The type of the pointer, e.g. int *, indicates to the compiler the type of the data stored at the address. Pointers allow a function to change objects in the function that called it. For example, compare:


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

    temp = x;
    x = y;
    y = temp;
  }
with
  void swap(int *px, int *py)
  {
    int temp;

    temp = *px;
    *px = *py;
    *py = temp;
  }


The version on the left fails because C passes arguments by value. But by passing the addresses of the arguments, e.g. swap(&a, &b), the contents of the addresses can be interchanged for the desired effect.

There is an elegant relationship in C between pointers and arrays: an array name is in fact a pointer. The first element of an array x[10] of doubles is x[0], which is equivalent to *x. The second element is x[1], equivalent to *(x + 1) (the compiler knows that x is a pointer to double, so x + 1 is an address one double further along in memory). This fact can be used to allocate arrays dynamically using malloc():

  double *x = (double *) malloc(10*sizeof(double));



Derek C. Richardson 2005-02-03