简体   繁体   English

将二维数组作为参数传递给函数

[英]Passing 2D array into a function as an argument

I am trying to pass 2D array into a function.我正在尝试将二维数组传递给函数。 Unfortunately I am stuck with pretty old compiler (gcc-4.1) and can't use any modern methods.不幸的是,我坚持使用相当老的编译器(gcc-4.1)并且无法使用任何现代方法。 After a bit of googling and stack over flow discussions.经过一些谷歌搜索和堆栈溢出讨论。 I came up with this.我想出了这个。 MatrixMN is own implementation of matrices

namespace MatrixMNTest {
//  Test variables

double matrix_4X2[4][2] = {{1, 2}, {3, 4}, {11, 12}, {0, 1}};

template <size_t size1, size_t size2>
MatrixMN getMatrix(const double (&arr)[size1][size2]) {
  MatrixMN m(size1, size2);
  for (unsigned i = 0; i < size1; ++i) {
    for (unsigned j = 0; j < size2; ++j) {
      m(i, j) = arr[i][j];
    }
  }
  return m;
}
}

int main() {

  size_t size1 = 4;
  size_t size2 = 2;
  // success 
  math::MatrixMN A = MatrixMNTest::getMatrix(MatrixMNTest::matrix_4X2);
  double scalar = 2.5;

  double result[size1][size2];
  memcpy(result, MatrixMNTest::matrix_4X2, sizeof(result));
  // fail
  math::MatrixMN B = MatrixMNTest::getMatrix(result);

}

I tried to run the same code both on gcc-4.1 and 7.5.0 to check the error message我尝试在 gcc-4.1 和 7.5.0 上运行相同的代码来检查错误消息

gcc-4.1 gcc-4.1

error: no matching function for call to 'getMatrix(double [(((unsigned int)(((int)size1) - 1)) + 1u)][(((unsigned int)(((int)size2) - 1)) + 1u)])'

gcc - 7.5.0海湾合作委员会 - 7.5.0

test.cpp: In function ‘int main()’:
test.cpp:96:52: error: no matching function for call to ‘getMatrix(double [size1][size2])’
   math::MatrixMN B = MatrixMNTest::getMatrix(result);
                                                    ^
test.cpp:69:16: note: candidate: template<long unsigned int size1, long unsigned int size2> math::MatrixMN MatrixMNTest::getMatrix(const double (&)[size1][size2])
 math::MatrixMN getMatrix(const double (&arr)[size1][size2]) {
                ^~~~~~~~~
test.cpp:69:16: note:   template argument deduction/substitution failed:
test.cpp:96:52: note:   variable-sized array type ‘long int’ is not a valid template argument
   math::MatrixMN B = MatrixMNTest::getMatrix(result)

Not sure..How to solve this.不确定..如何解决这个问题。 Any help is greatly appreciated.任何帮助是极大的赞赏。

I modified the code to..我将代码修改为..

const size_t size1 = 4;
const size_t size2 = 2;

double result[size1][size2];

or pass them directly.或直接传递它们。

double result[4][2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM