如何将二维数组的引用传递给函数? [英] How do I pass a reference to a two-dimensional array to a function?
问题描述
我正在尝试将二维数组的引用传递给 C++ 中的函数.我知道编译时两个维度的大小.这是我现在所拥有的:
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
但这行不通.我从 g++ 得到这个错误:
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]);
一起做
void do_something(int array[board_width][board_height]);
实际上会传递一个指向二维数组的第一个子数组的指针(board_width"被完全忽略,就像当你有 int array[]
接受一个指针),这可能不是您想要的(因为您明确要求提供参考).因此,使用引用进行操作,在参数 sizeof array
上使用 sizeof 将产生 sizeof(int[board_width][board_height])
(就像你会在参数本身)同时使用第二种方法(将参数声明为数组,从而使编译器将其转换为指针)将产生 sizeof(int(*)[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.
这篇关于如何将二维数组的引用传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!