我试图传递二维数组的函数,但有两个错误,我不知道为什么。我有一些关于函数传递二维数组的文章,但也不明白为什么我失败了。
#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) {}发布于 2020-06-23 06:34:24
要将函数double传递给参数double**的多维matrixSwap()数组matrix实际上并不表示多维数组。
正确地使用数组,如下所示:
#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是否通过新参数成功地传递到函数中。
https://stackoverflow.com/questions/62528551
复制相似问题