Node:Arrays as Parameters, Next:, Previous:Initializing arrays, Up:Arrays



Arrays as Parameters

There will be times when you want to pass an array as a parameter to a function. (For example, you might want to pass an array of numbers to a function that will sort them.)

In the following example, notice how the array my_array in main is passed to the function multiply as an actual parameter with the name my_array, but that the formal parameter in the multiply function is defined as int *the_array: that is, an integer pointer. This is the basis for much that you will hear spoken about the "equivalence of pointers and arrays" -- much that is best ignored until you have more C programming experience. The important thing to understand is that arrays passed as parameters are considered to be pointers by the functions receiving them. Therefore, they are always variable parameters, which means that other functions can modify the original copy of the variable, just as the function multiply does with the array my_array below. (See Parameters.)

#include <stdio.h>

void multiply (int *, int);


int main()
{
  int index;
  int my_array[5] = {0, 1, 2, 3, 4};

  multiply (my_array, 2);

  for (index = 0; index < 5; index++)
    printf("%d  ", my_array[index]);

  printf("\n\n");
  return 0;
}


void multiply (int *the_array, int multiplier)
{
  int index;
  for (index = 0; index < 5; index++)
    the_array[index] *= multiplier;
}

Even though the function multiply is declared void and therefore does not return a result, it can still modify my_array directly, because it is a variable parameter. Therefore, the result of the program above is as follows:

0  2  4  6  8

If you find the interchangeability of arrays and pointers as formal parameters in function declarations to be confusing, you can always avoid the use of pointers, and declare formal parameters to be arrays, as in the new version of the multiply function below. The result is the same.

void multiply (int the_array[], int multiplier)
{
  int index;
  for (index = 0; index < 5; index++)
    the_array[index] *= multiplier;
}