Passing multi-dimensional arrays
August 18th, 2009 § 1 Comment
Today, a somewhat basic post.
Suppose you have a multi-dimensional array and would like to pass it to a function, but still be able to access it easily (by using row,col tuples for instance): passing the pointer is probably not the right way to go (although you could cast inside, but that’s ugly).
Here’s a quick example using an array of 2 dimensions:
void f (int arr[][5]) {
// success
}
int main () {
int arr[3][5];
f(arr);
return 0;
}
Needless to say that this syntax can easily be extended to any multi-dimensional array.
The correct way to pass an array to a function and have
* all its dimensions available
* type safety (passing array of different dimensions generates a compile-time error)
is to pass the array by reference, like this:
void foo(int (&ref_arr)[3][5]) {
}
Parentheses are required because of operator precedence.
This works because arrays decay to pointers when passed to functions (and thus, void f(int arr[3]) is equivalent to void f(int arr[])), whereas references to arrays don’t – and they form a distinct type which is not convertible to reference-to-array of another dimension