【问题标题】:cannot convert ‘int (*)[L][W]’ to ‘int*’无法将“int (*)[L][W]”转换为“int*”
【发布时间】:2021-12-14 14:12:12
【问题描述】:

我试图在 void 函数参数中引用二维数组,该函数将在主函数中调用,但出现以下错误:

mmm.cpp:26:31: error: cannot convert ‘int (*)[L][W]’ to ‘int*’
                                     ^~~~~~~~~~~~~~~

这是我的代码:

#include <iostream>
#include <ctime>
using namespace std;

void generateRandemMatrix(int L ,int W , int * arr[L][W] ){


   for (int i=0; i<L; i++){

    for (int j=0; j<W; j++){
        arr[i][j] = rand();
    }

   }

 }

int main() {

int *p;
int L = 10;
int W = 10;
int arr[L][W];
generateRandemMatrix(L,W, &arr);

}

【问题讨论】:

  • int arr[L][W]; 是 VLA,不是标准 C++。如果 LW 不是常量表达式 (constexpr),请改用 std::vector&lt;std::vector&lt;int&gt;&gt;
  • 这是您在编译时遇到的第一个错误吗? (当我复制和编译您的代码时,这不是为我准备的。)您应该在担心其他错误之前解决第一个错误,因为其他错误可能(在您的情况下肯定是)早期错误的工件。

标签: c++ pointers function-pointers


【解决方案1】:

没有 std::vector

void generateRandemMatrix(size_t L, size_t W, int *a)
{
    int (*arr)[W] = (int (*)[W])a;

    for (size_t i = 0; i < L; i++)
    {
        for (size_t j = 0; j < W; j++)
        {
            arr[i][j] = rand();
        }
   }

 }

int main() {

    int *p;
    size_t L = 10;
    size_t W = 10;
    int arr[L][W];
    generateRandemMatrix(L,W, &arr[0][0]);

}

【讨论】:

  • int (*arr)[W] = (int (*)[W])a; 不是有效的 C++。它依赖于 gcc 默认拥有的 VLA 扩展。
  • 如果你要玩这样的指针游戏,至少使用void *a 作为参数类型。这警告读者,有一些类似 C 的东西正在发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多