cplusplus.co.il

Passing multi-dimensional arrays

Posted on: 18/08/2009

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.

Advertisements

1 Response to "Passing multi-dimensional arrays"

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: