Passing Arrays to Functions

It is not difficult to pass arrays to functions, but it is more challenging to understand why we use the syntax that we do.  We will work to understand the syntax in the coming weeks, but for now, you can pass arrays in the following way.

Inside of the function where you would put the name of the parameter being passed you should use the following format:

void myfunction(apvector<type> & name)

Where myfunction is the name of your function, type is the variable type (int, apstring etc.) and name is the name of the array.  Note the addition of the ampersand (&) and that there are no parantheses indicating the size of the array after the array name.  To pass an array to the function you use the followign syntax.

myfuntion(name);

Where myfunction is the name of your function, and name is the name of the array.  Again, note that the array size is not used in the passing of the array.   The basic reason for this is that the computer tells the function where to find the information in the array, rather than passing the array itself.  We will discuss this problem further soon.

An example of passing arrays to functions is shown here:


  #include <iostream.h>

  #include <apstring.h>

  int add(apvector<int> & numbers)

  {

      return numbers[0]+numbers[1];

  }



  void main(void)

  {

      apvector<int> values(2);

      cin>>values[0];

      cin>>values[1];

      cout<<add(values);

  }

WB01624_.gif (281 bytes) Back to Assignment 8