ARRAYS AS FUNCTION PARAMETERS

Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to the required textbook.

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 array–id 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:
#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:
#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 multi–dimensional arrays as function parameters, the maximum values of all dimensions except the first must be specified in the function definition heading.


© 1994-07-23 cpsm; last update 2005-01-23