So far, we've seen two ways of passing information into functions : call by
value and call by reference. When we pass arrays into functions, it is
always call by reference (at least for the scope of this course).
As we shall see, there is no & character, but the array is still
passed by call by reference.
Consider the following :
// file : pass.C
#include <iostream.h>
const int size=5;
void print(int n[size])
{
int i;
for (i=0 ; i<size ; i++)
cout << n[i] << " ";
cout << endl;
}
void change(int n[size])
{
int i;
for (i=0 ; i<size ; i++)
n[i] = 10 + i;
}
int main()
{
int A[size];
int i;
for (i=0 ; i<size ; i++)
A[i] = i*i;
print(A);
change(A);
print(A);
return 0;
}
Here's an example of how to pass a two dimensional array into a function :
// file : pass_2d.C
#include <iostream.h>
const int ROWS=3; const int COLS=2;
void change(int a[ROWS][COLS])
{
int r,c;
for (r=0 ; r<ROWS ; r++)
for (c=0 ; c<COLS ; c++)
if (c*r % 2 == 0)
a[r][c]=1;
}
void print(int a[][COLS])
{
int r,c;
for (r=0 ; r<ROWS ; r++)
{
for (c=0 ; c<COLS ; c++)
cout << a[r][c] << " ";
cout << endl;
}
}
int main()
{
int X[ROWS][COLS];
int r,c;
for (r=0 ; r<ROWS ; r++)
for (c=0 ; c<COLS ; c++)
X[r][c]=0;
change(X);
print(X);
return 0;
}
Note that when passing an N-dimensional array into a function, you may
leave the first dimension's size in the formal parameter list empty. The
compiler is smart enough to figure this out.