简体   繁体   中英

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

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?

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

Syntax is not correct.

Lets take an example of 1D Array

 int a[] = {1,2,3};
 int (&p) [3] = a; // p is pointing array a 

So you can do same for 2D array as shown below

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM