tags:

views:

2855

answers:

5

I am trying to pass a reference to a two-dimensional array to a function in C++. I know the size of both dimensions at compile time. Here is what I have right now:

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

But this doesn't work. I get this error from g++:

error: expected ‘,’ or ‘...’ before ‘*’ token

What does this error mean, and how can I fix it?

A: 

I think this is what you want:

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

You can't pass an array of references to a function.

yjerem
+6  A: 

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.

Johannes Schaub - litb
A: 

@litb That works. Thanks!

You should accept his answer then (little checkmark icon next to it). Posting a reply as a separate answer won't necessarily be seen (doesn't show up in his profile)
Shog9
+1  A: 

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
Mr.Ree
A: 

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.

Charles Bailey