将动态分配的多维数组传递给函数

时间:2017-10-14 19:02:35

标签: c++ arrays multidimensional-array

#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)'

1 个答案:

答案 0 :(得分:1)

#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