在函数中传递二维数组
Pass two dimensional array in function
我正在尝试在函数中传递二维数组,但是有两个我不知道为什么的错误。我有一些关于在函数中传递二维数组的文章,但也不明白为什么我失败了。
#include <iostream>
using namespace std;
// prototypes
void matrixSwap(double** matrix, int rows, int columns);
int main()
{
const int ROWS = 5;
const int COLUMNS = 5;
double matrix[ROWS][COLUMNS] =
{
{ 1, 2, 3, 4, 5},
{ 6, 7, 8, 9, 0},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
matrixSwap(matrix, ROWS, COLUMNS);
/* it says
1) argument of type "double (*)[5U]" is incompatible with parameter of type "double **"
2) 'void matrixSwap(double *[],int,int)': cannot convert argument 1 from 'double [5][5]' to 'double *[]'
*/
}
void matrixSwap(double** matrix, int rows, int columns) {}
您尝试传入函数matrixSwap()
的多维double
数组matrix
double**
,实际上并不表示多维数组。
正确使用数组,如下所示:
#include <iostream>
using namespace std;
const unsigned short MAXROWS = 5;
// prototypes
void matrixSwap(double matrix[][MAXROWS], int rows, int columns);
int main()
{
const int ROWS = 5;
const int COLUMNS = 5;
double matrix[ROWS][COLUMNS] =
{
{ 1, 2, 3, 4, 5},
{ 6, 7, 8, 9, 0},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
matrixSwap(matrix, ROWS, COLUMNS);
}
void matrixSwap(double matrix[][MAXROWS], int rows, int columns) {}
刚刚更改为[][MAXROWS]
其中MAXROWS
包含一个值为5
的无符号整数。
声明:
void matrixSwap(double matrix[][MAXROWS], int rows, int columns)
相当于:
void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns)
请注意,这里我使用了*matrix
,然后附加了与matrix[][MAXROWS]
相同的工作[MAXROWS]
。
因此,您可以通过以下另一种方式执行相同的操作:
void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns) {
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
std::cout << matrix[i][j] << ' ';
}
std::cout << std::endl;
}
}
这将为您提供输出:
1 2 3 4 5
6 7 8 9 0
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
查看新参数是否成功将matrix
传递到函数中。
相关文章:
- 在函数中传递二维数组
- C++函数中推广二维数组
- 如何将 50 行和 50 列的二维数组编码为一个为元素随机分配星号的函数?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 如何在 c++ 中初始化构造函数中的二维数组
- 编写一个可以使二维数组平坦的函数
- 二维数组传入没有全局定义 (M x N) 的函数
- 如何将二维数组作为类中的私有变量,然后在构造函数中设置它
- 如何在函数中将二维数组作为参数传递,并在 C++ 中返回二维数组
- 类的二维数组和C++中的构造函数调用
- 将二维数组传递到只需要一维数组的函数中(C++)
- 接受来自函数的二维数组(int 类型)并将其返回到主函数
- 二维数组的递归函数
- 如何制作返回C 中二维数组的函数
- 通过指针将二维数组传递给 c++ 中的函数
- C++:传递二维数组以执行函数
- 如何在C++中将动态二维数组传递给函数
- 将二维数组从数据文件传递给函数并输出内容
- 将二维数组传递给函数会产生奇怪的错误
- 二维数组 - 函数