尝试创建一个函数,该函数以表格格式传递2d数组输出数组(类似于python3的tabulate) &



因此,我试图创建一个函数,该函数将2d数组作为输入以及行和Cols变量,并以表格式输出数组的内容。这是我目前看到的

#include <iostream>
using namespace std;
void Tabulate(int *x[][], int xRows, int xCols) {
for (int i = 0; i < xRows; i++) {
for (int j = 0; j < xCols; j++) {
cout << x[i][j] << "t";
}
cout << endl;
}
}
int main() {
int rows = 2;
int cols = 3;
int x[rows][cols] = {{2,3,4}, {8,9,10}};
Tabulate(x, rows, cols); 
}

这里是返回的错误

tabulate.cpp:4:20: error: declaration of ‘x’ as multidimensional array must have bounds for all dimensions except the first
4 | void Tabulate(int *x[][], int xRows, int xCols) {
|                    ^
tabulate.cpp:4:25: error: expected ‘)’ before ‘,’ token
4 | void Tabulate(int *x[][], int xRows, int xCols) {
|              ~          ^
|                         )
tabulate.cpp:4:27: error: expected unqualified-id before ‘int’
4 | void Tabulate(int *x[][], int xRows, int xCols) {
|                           ^~~
make: *** [<builtin>: tabulate] Error 1

我知道它必须与定义数组的第二次元的语法,但我有困难找到任何为我的具体情况。对不起,如果这是愚蠢的东西,我错过了,但我很感激的帮助:/.

您正在尝试将2D数组传递给函数。在这种情况下,你的数组要么是动态的,要么是一维常量。

使用:

void Tabulate(int **x, int xRows, int xCols) //dynamic array

在这里查看更多细节/方法(这里有一些非常好的答案):将2D数组传递给c++函数

最新更新