Entire Arrays as Function Arguments

  1. An entire array can be used as a formal or actual argument of a function.

  2. The syntax for the prototype of such a function is:

    Type_Returned Function_name( ..., Base_Type Array_Name[ ], ...);

  3. The names of formal parameters are optional in a function prototype, however the square brackets cannot be omitted for array arguments.

  4. For example, the following is a valid function prototype:

    void sum_array(int&, int [ ], int);

  5. An array formal argument behaves almost like a call-by-reference argument in that when the function is called with an array as argument, the address of the first element of the that array is passed to the function together with the array base type. However the size of the array is not passed to the function. Very often, the array's actual size or its maximum declared size is passed to the function as a separate call-by-value argument.

  6. When a function having an array argument is invoked, only the name of the array (without the square bracket) is used as actual argument.

  7. //This example illustrates how to define and
    //use a function that has an array argument.
    //Reads in 5 scores and echos them. Demonstrates the function fill_up.
    #include <iostream>
    using namespace std;

    void fill_up(int a[ ], int soMany);
    //Precondition: soMany is the declared size of the array a.
    //The user will type in soMany integers.
    //Postcondition: The array a is filled with soMany integers
    //from the keyboard.

    int main( )
    {
       int i, a[5];

       fill_up(a, 5);

       cout << "Echoing array:\n";
       for (i = 0; i < 5; i++)
         cout << a[i] << endl;

       return 0;
    }

    //Uses iostream:
    void fill_up(int a[ ], int soMany)
    {
       cout << "Enter " << soMany << " numbers:\n";
       for (int i = 0; i < soMany; i++)
           cin >> a[i];
    }

  8. Since the size of the array is not automatically passed to a function, and the array size is passed as a separate parameter of the function, the function fill_up can be used to fill an array of any size. For example,

    int score[5], temperature[10];
    fill_up(score,5);
    fill_up(temperature,8);      //Don't have to fill up the entire array