C++ Notes: Passing Array Parameters

Array variables as parameters

When an array is passed as a parameter, only the memory address of the array is passed (not all the values). An array as a parameter is declared similarly to an array as a variable, but no bounds are specified. The function doesn't know how much space is allocated for an array. See the example below.

Example -- Function to add numbers in an array

This main program calls a function to add all the elements in an array and uses the returned value to compute the average.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
// arrays/average.cpp - Averages numbers
// Fred Swartz - 2003-11-20

#include <iostream>
using namespace std;

float sum(const float x[], const int size); // prototype

//====================================================== main
int main() {
    float a[1000];     // Declare an array of 1000 floats
    int n = 0;         // number of values in a.

    while (cin >> a[n]) {
        n++;
    }
    
    cout << "Average = " << sum(a, n)/n << endl;
    
    return 0;
}


//======================================================= sum
// sum adds the values of the array it is passed.
float sum(const float x[], const int size) {
    float total = 0.0;  // the sum is accumulated here
    for (int i=0; i<size; i++) {
        total = total + x[i];  
    }
    return total;
}

Because this application reads an unbounded number of values, it is subject to buffer overflow, trying to read more values into an array than will fit. A more appropriate data structure to use is a vector, which will expand as necessary to accomodate data. See Passing Vectors as Parameters.