How do I pass a reference to a two-dimensional array to a function?

If you know the size at compile time, this will do it:

//function prototype
void do_something(int (&array)[board_width][board_height]);

Doing it with

void do_something(int array[board_width][board_height]);

Will actually pass a pointer to the first sub-array of the two dimensional array ("board_width" is completely ignored, as with the degenerate case of having only one dimension when you have int array[] accepting a pointer), which is probably not what you want (because you explicitly asked for a reference). Thus, doing it with the reference, using sizeof on the parameter sizeof array will yield sizeof(int[board_width][board_height]) (as if you would do it on the argument itself) while doing it with the second method (declaring the parameter as array, thus making the compiler transform it to a pointer) will yield sizeof(int(*)[board_height]), thus merely the sizeof of a pointer.


Although you can pass a reference to an array, because arrays decay to pointers in function calls when they are not bound to a reference parameters and you can use pointers just like arrays, it is more common to use arrays in function calls like this:

void ModifyArray( int arr[][80] ); 

or equivalently

void ModifyArray( int (*arr)[80] );

Inside the function, arr can be used in much the same way as if the function declaration were:

void ModifyArray( int (&arr)[80][80] );

The only case where this doesn't hold is when the called function needs a statically checked guarantee of the size of the first array index.


You might want to try cdecl or c++decl.

% c++decl
c++decl> declare i as reference to array 8 of array 12 of int
int (&i)[8][12]
c++decl> explain int (&i)[8][12]
declare i as reference to array 8 of array 12 of int
c++decl> exit