Arrays As Argument
To pass an array as an argument to a function, the parameter must be a pointer
to the array element type. Given the array:
int tenElArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
in order to pass it to a function as an argument, the function's definition must be as follows:
void manipulateArray(int* array)
{
// function body
}
the array is passed as a pointer to the first element. To call the function you need to write:
manipulateArray(tenElArray);
In fact,
tenElArray represents the pointer to
the first element of the array. Beware, though, that in order not to go out of
bound when manipulating the array, you need to know the size of it in advance,
because except for null-terminated strings, arrays have no element indicating
the end of them.
Example
#include <iostream>
using namespace std;
void printArray(int* array) // function taking an int array as an argument
{
for(unsigned i = 0; i < 10; i++)
cout << array[i] << " ";
cout << endl;
}
int main()
{
// declare an array of ten int
int tenElArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printArray(tenElArray);
}
Output
1 2 3 4 5 6 7 8 9 10