How do I pass an array to a function? How do I return it?
The C/C++ compiler treats the name of an array as the address of where the array starts in memory. An array name is effectively a "constant pointer" - it can be used like a pointer, but you are not allowed to change it.
If you call a function with an array name as an argument, then the corresponding parameter in the function gets the address of the array upon entry into the function. Subscripting this parameter name is then subscripting into the caller's array. So the array is not copied, only its starting address is given to the function.
You have to tell the compiler that the parameter is an array, but the size of the array doesn't matter (for 1-D arrays), since only the address of where the array starts is needed (C/C++ doesn't keep track of how long the
array is - that's *your* problem). There are complications when more dimensions are involved.
Since the function is actually accessing the caller's array, it can put values into it that the caller then gets when the function returns. There is no way in C/C++ to return an array-type variable from a function. So to give array values back to a caller, you always modify the caller's array.
For example:
int main()
{
int ary[10]; // caller declares a one-dimensional array of ints
ary[3] = 5; // put a value of 5 into the fourth cell
foo(ary); // call foo with the array name, which is starting address of array
cout << ary[3] << endl; // output value put there by foo, which is 8
}
// declare parameter of foo to be an array of ints -
// size of the array does not have to be specified - ignored if it is
void foo(int a[] )
{
a[3] = a[3] + 3; // add 3 to the value in the 4th cell of caller's array
return;
}
Some more explanation
Since an array name is a constant pointer to where the array starts, you can also use a pointer-type parameter in the function and get the same result.
So this definition of foo would also work:
// foo takes an argument of type pointer to int
void foo(int * a )
{
a[3] = a[3] + 3; // add 3 to the value in the 4th cell of caller's array
return;
}
This approach is very heavily used with C strings, as you will see.
Cs dirty secret about arrays
The C/C++ compiler actually translates the subscripting operator directly into pointer expressions. Check your lecture notes from 100 - did you see the following?
a[i] is the same thing as *(a + i)
Later we will go over what is involved with passing multidimensional arrays as function parameters, and some stupid pointer tricks with arrays.