error: cannot convert 'int* (*)[10]' to 'const int* (*)[10]'

error: cannot convert 'int* (*)[10]' to 'const int* (*)[10]'

我在传递非 const 二维指针数组作为函数的 const 参数时遇到问题。但是我收到一个错误。我不明白为什么。

// Online C++ compiler to run C++ program online
#include <iostream>

void test(const int  *arrayPtr[][10]){}
//void test(int  * const arrayPtr[][10]){//Works DO NOT USE //}

int main() {
 int *arrayPtr[10][10] = {};
 test(arrayPtr);
 std::cout <<"done" << std::endl;
 return 0;
}

g++ /tmp/JYRlXRFoja.cpp /tmp/JYRlXRFoja.cpp: In function 'int main()': /tmp/JYRlXRFoja.cpp:11:7: error: cannot convert 'int* (*)[10]' to 'const int* (*)[10]'    11 |  test(arrayPtr);
      |       ^~~~~~~~
      |       |
      |       int* (*)[10] /tmp/JYRlXRFoja.cpp:5:42: note:   initializing argument 1 of 'void test(const int* (*)[10])'
    5 | void test(const int                     *arrayPtr[][10]){
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~

您的代码中有两个错误。

  1. 您传递的是 int* array[][],而不是 const int* array[][]。所以将函数参数改为int* array[][10].
  2. 您受到 array decay 的约束。要解决此问题,您应该通过引用传入数组。为此你的函数参数应该是这样的:int* (&arrayPtr)[][10].

你的错误是不言自明的,它说明了问题所在。如果你仔细阅读它,它说你将 int* (*)[10] 传递给 const int* (*)[10] 类型的容器。