c++ - 在函数中传递二维数组
问题描述
我试图在函数中传递二维数组,但是有两个我不知道为什么的错误。我有一些关于在函数中传递二维数组的文章,但也无法理解我为什么会失败。
#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) {}
解决方案
您尝试将函数传递给参数的多维double
数组实际上并不代表多维数组。matrix
matrixSwap()
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]
whereMAXROWS
包含一个无符号整数 value 5
。
声明:
void matrixSwap(double matrix[][MAXROWS], int rows, int columns)
相当于:
void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns)
请注意,我在这里使用*matrix
然后附加[MAXROWS]
了与matrix[][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
新参数是否成功传递给函数。
推荐阅读
- docker - pgAdmin4 中的文件浏览器弹出窗口在哪里寻找文件?
- flutter - Flutter - AlertDialog 弹出但不显示其内容
- reactjs - 是否有支持 react.js 的编辑 pdf 字段、创建表单和提交的工具?
- asp.net-core - 如何重新启动 Hangfire 服务器,或停止它并启动一个新服务器,以更改它正在处理的队列?
- postgrest - GET 方法错误地使用 volatile PostgREST RPC 函数?
- python - 为什么我不能在设置深度方向的字母后使用 tensorflow 2.3.1 加载模型权重
- jenkins-pipeline - 如何从 Jenkins 访问远程 Windows 文件系统
- java - 更改 Liquibase - 找不到数据库驱动程序:com.mysql.cj.jdbc.Driver
- powerbi - Power BI:需要计算最近 3 个月的 MTD 销售额
- django - 如何更新主键,外键指向什么,没有“ON UPDATE CASCADE”