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.

Leave a Comment