
Using call by value is a very inefficient method of passing arrays as parameters to functions. In C++, arrays are always passed as reference parameters. Hence, there is no need to explicitly indicate the manner in which arrays are passed, i.e. with &, as you normally would need with single variables. In the function declaration where the array is a parameter, the type referring to the array is followed by a pair of brackets, i.e. [ ]. In a function call, only the arrayid is needed. In the function definition heading where the array is a parameter, the array name is followed by a pair of empty brackets.
| EXAMPLE 069: |
#define MaxDeg 9;
void main (void); void main (void) _ _ { _ _ _ _ double Horners (double [ ], int, double); ¬ function declaration _ _ _ _ int deg; _ _ _ _ double fx, x; _ _ _ _ double Coef [MaxDeg + 1]; ¬ array declaration _ _ _ _ . . . _ _ _ _ fx = Horners (Coef, deg, x); ¬ function call _ _ _ _ return; _ _ } double Horners (double c [ ], int d, double x) ¬ function definition heading _ _ { _ _ _ _ double y; _ _ _ _ int i; _ _ _ _ y = 0; _ _ _ _ for (i = d; i >= 0; i ) _ _ _ _ _ _ { _ _ _ _ _ _ _ _ y = y * x + c [ i ]; _ _ _ _ _ _ } _ _ _ _ return (y); _ _ } |
When the array being passed as a parameter is a 2 dimensional array, attention has to be given to the way the array is stored in memory. Although we think of a 2 dimensional array as consisting of rows and columns, it is actually linearly stored. For example, if given the following:
| a00 | a01 | a02 | a03 |
| a10 | a11 | a12 | a13 |
| a20 | a21 | a22 | a23 |
It is actually contiguously stored in a linear fashion by rows:
| a00 | a01 | a02 | a03 | a10 | a11 | a12 | a13 | a20 | a21 | a22 | a23 |
Hence, the maximum value of the second dimension of the array must be specified in the function definition heading to insure proper access of data.
| EXAMPLE 070: |
#define m . . .
#define n . . . void main (void) _ _ { _ _ _ _ void Solve (float [ ][ ], int); ¬ function declaration _ _ _ _ double a [m][n]; ¬ array declaration _ _ _ _ . . . _ _ _ _ Solve (a, k); ¬ function call _ _ _ _ . . . _ _ _ _ return; _ _ } void Solve (float a [ ][n], int k) ¬ function definition heading _ _ { _ _ _ _ int i, j; _ _ _ _ . . . _ _ _ _ for ( i = 0; i <= k; i++ ) _ _ _ _ _ _ { _ _ _ _ _ _ _ _ for ( j = 0; j <= n; j++ ) _ _ _ _ _ _ _ _ _ _ { _ _ _ _ _ _ _ _ _ _ _ _ a [ i ][ j ] = . . . _ _ _ _ _ _ _ _ _ _ } _ _ _ _ _ _ } _ _ . . . _ _ _ _ return; _ _ } |
When passing multidimensional arrays as function parameters, the maximum values of all dimensions except the first must be specified in the function definition heading.
Review Questions on Arrays as Function
Parameters
( Check the calendar for the due date )