In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function:
|
accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:
|
it would be enough to write a call like this:
|
Here you have a complete example:
| 5 10 15 2 4 6 8 10 |
As you can see, the first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range.
In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:
|
for example, a function with a multidimensional array as argument could be:
|
Notice that the first brackets [] are left blank while the following ones are not. This is so because the compiler must be able to determine within the function which is the depth of each additional dimension.
Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.