将动态分配的多维数组传递给函数
Pass a dynamically allocated multidimensional array to a function
#include<iostream>
using namespace std;
void seed(int* matrixAddr, int n, int m);
void main()
{
int n, m;
cin >> n >> m;
int matrix[n][m]; // DevC++ does not throw an error here, where VS does instead
seed(matrix, n, m);
}
void seed(int* matrixAddr, int n, int m) {}
直接访问matrix
意味着引用内存地址 - 在这种情况下,引用二维数组的第一个元素。
但是,显然,地址不能按原样传递给seed
函数,该函数接受指针作为其第一个参数。
为什么会这样?这不应该被允许吗?
DevC++ 引发的错误如下:[Error] cannot convert 'int (*)[m]' to 'int*' for argument '1' to 'void seed(int*, int, int)'
#include <iostream>
using namespace std;
void seed(int** matrixAddr, int n, int m);
int main()
{
int rows, cols;
int **matrix = NULL;
cin >> rows >> cols;
matrix = new int*[rows];
for(int i = 0; i < rows; i++)
matrix[i] = new int[cols];
seed(matrix, rows, cols);
return 0;
}
void seed(int** matrixAddr, int rows, int cols) {
cout << "It is OK" ;
}
您可以从这里查看 http://rextester.com/PULAXL63031
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中