use*_*730 1 c++ methods multidimensional-array
我正在用 C++ 编写康威的生命游戏。我收到一个编译时错误,这与我将二维数组传递给方法的方式有关:
gameoflife.cpp:5:25: error: array has incomplete element type 'int []'
void print_game(int game[][], int SIZE);
gameoflife.cpp:6:23: error: array has incomplete element type 'int []'
void run_game(int game[][], int SIZE);
gameoflife.cpp:7:23: error: array has incomplete element type 'int []'
void set_cell(int game[][], int i, int j, int next[][], int SIZE);
Run Code Online (Sandbox Code Playgroud)
等等。
我的代码的开头是:
void print_game(int game[][], int SIZE);
void run_game(int game[][], int SIZE);
void set_cell(int game[][], int i, int j, int next[][], int SIZE);
Run Code Online (Sandbox Code Playgroud)
显然问题从这里开始。
在方法中传递二维数组有什么问题?我应该改用 ** 吗?
在方法中传递二维数组有什么问题?我应该使用 a
**吗?
不是真的 - 如果可能,您应该使用std::vector向量,如下所示:
#include <vector>
...
void print_game(std::vector<std::vector<int> > game) {
... // No need to pass the size
}
Run Code Online (Sandbox Code Playgroud)
传递内置二维数组将要求您将两个维度之一指定为常量,或者将数组分配为指针数组,然后将指针传递给指针(即int **)。这些选择都不是最佳选择:第一个将数组限制为编译时最大值,而第二个则要求您进行大量的手动内存管理。