c - 如何将非 const 动态多维数组传递给需要 const 多维数组的函数?

标签 c multidimensional-array dynamic parameter-passing constants

我在 C 中编写了以下函数来打印出动态创建的矩阵,但保证在函数内部我

  1. 无法修改给我的指针
  2. 不能修改任何内部指针
  3. 不能修改矩阵中的任何数字

 void const2dPrinter(const int *const *const mat, const int numRows, const int numCols){
  for(int i =0; i < numRows; ++i){
    for(int j =0; j < numCols; ++j){
      printf("%d ", mat[i][j]);
    }
    printf("\n");
  }
 }

我尝试如下调用 main 中的函数

int main(){
  int numRows = 3;
  int numCols = 4;
  int** mat = (int**) malloc(numRows * sizeof(int*);
  for(int i = 0; i < numRows; ++i){
    mat[i] = (int*)malloc(numCols * sizeof(int));
    for(int j = 0; j < numCols; ++j){
      mat[i][j] = (i +1) * (j+1);
    }
  }
  const2dPrinter(mat, numRows, numCols);
...
}

但是我从编译器中得到以下错误

error: passing argument 1 of 'const2dPrinter' from incompatible pointer type [-Werror=incompatible-pointer-types]
   const2dPrinter(mat, numRows, numCols);
note: expected 'const int * const* const' but argument is of type 'int **'
   void const2dPrinter(const int *const *const const mat, const int numRows, const int numCols)

我的 IDE 出现以下错误:

Parameter type mismatch: Assigning int** to const int* const* const* discards const qualifier. 

如果我删除函数声明中的第一个 const,代码将正常工作。从 void const2dPrinter(const int *const *const mat, ...){

到 void const2dPrinter(int *const *const mat, ...){

但随后我可以修改 const2dPrinter 中矩阵的值,这是我不希望能够做到的。

我知道我可以在调用函数时将 int** 转换为 const int *const *const,如下所示,但我我对为什么我现在拥有的东西不起作用感到非常困惑,因为我读过的所有内容都说你应该能够让一个 const 指针指向一个非 const 值。

const2dPrinter((const int* const* const) mat, numRows, numCols); //this works 

我曾尝试寻找解决方案,但未能找到。该代码将在 C++ 编译器上编译而不会出现问题,但不适用于我的 C 编译器 (gcc)。

如能提供任何有关如何解决我的问题的建议以及解释为什么我现在所拥有的无法正常工作,我们将不胜感激。

最佳答案

您必须编写丑陋的类型转换(尽管最后一个 const 是多余的)。 C 规范中的一个疏忽,没有将 T ** 更改为 T const * const * 的隐式转换。

我认为在实践中,由于这个问题,人们倾向于在存在指向指针的指针或指向数组的指针的情况下不使用 const。您可以使用强制转换和/或通用选择器等来解决它。但事情似乎很快就会变得复杂,无法支持本应是简单的操作。


对于您的具体情况,另一种方法可能是使用一维数组来存储矩阵。 (由于需要较少数量的分配,这在运行时可能会更有效率)。

关于c - 如何将非 const 动态多维数组传递给需要 const 多维数组的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433087/

相关文章:

c - 未收到 ARP 请求,wireshark 无法读取 arp header

c++ - 如何在 SQLite3 中查找 stmt 到行号?

c - 根据 C 中二维数组中列中的值重新排列行

objective-c - 使用具有未知键的 NSDictionaries 动态填充 NSTableView

javascript - 如何动态管理不同布局的样式表?

c - 使用 Bison 解析错误

从另一个进程关闭 XLib 应用程序

php - 检查数组值是否存在于 PHP 多维数组中

ruby - 如何从数组中生成数组的 Ruby 哈希

javascript - 通过字符串到达​​嵌套方法的最佳方法