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


Question

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?

1
25
12/31/2008 11:03:39 PM

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.

36
12/31/2008 11:17:04 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon