c++ - 解决此错误时出现问题。我正在努力在主函数中传递数组

标签 c++ pointers matrix multidimensional-array compiler-errors

#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 6

int PrintSpiral(int arr[][C], int m, int n){
    int t= 0, b = m-1, l = 0, r = n-1;
    int dir = 0;`
    while(l <= r && t <= b){
        if(dir == 0){
            for(int k = l; k <= r; k++)
                cout << arr[t][k];
            t++;
        }
        else if(dir == 1){
            for(int k = t; k <= b; k++)
                cout << arr[k][r];
            r--;
        }
        else if(dir == 2){
            for(int k = r; k >= l; k--)
                cout << arr[b][k];
            b--;
        }
        else if(dir == 3){
            for(int k = b; k >= t; k--)
                cout << arr[k][l];
            l++;
        }
        dir = (dir+1)%4;
    }
}

int main() {
    //code
    int t;
    cin>>t;
    while(t--){
        int na,ma;
        cin>>na>>ma;
        int ar[na][ma] = {{0}};
        for(int i = 0; i < na; i++){
            for(int j = 0; j < ma; j++){
                cin>>ar[i][j];
            }
        }
        PrintSpiral(ar,na,ma);
    }
    return 0;
}

我收到此错误:
Spiral_matrix.cpp: In function 'int main()':<br/>
Spiral_matrix.cpp:47:18: error: cannot convert 'int (*)[ma]' to 'int (*)[6]'
      PrintSpiral(ar,na,ma);
                  ^~
Spiral_matrix.cpp:6:21: note:   initializing argument 1 of 'int PrintSpiral(int (*)[6], int, int)'
 int PrintSpiral(int arr[][C], int m, int n){

enter image description here

解决问题时出错。请调查一下
上面的代码将给定的二维矩阵打印到
螺旋形式
我应用了带有随机值的arr[][6],并且我将预定义列应用为C
并再次使用arr[][C]更新它仍然显示错误
除此之外,我甚至在我的主要功能中使用了R和C的值
仍然显示错误
我想要一种可以在主函数中成功传递函数的方法。

最佳答案

这是您的代码,重写为使用 vector 而不是可变长度数组。我已经省略了不需要更改的部分(大部分是)

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

void PrintSpiral(const vector<vector<int>>& arr){
    if (arr.size() == 0) return;
    int t= 0, b = arr.size()-1, l = 0, r = arr[0].size()-1;
    ...
}

int main() {
    ...
        int na,ma;
        cin>>na>>ma;
        vector<vector<int>> arr(na, vector<int>(ma));
        ...
        PrintSpiral(arr);
    ...
    return 0;
}

您越早了解现代C++(std::vector已有20多年的历史了),您的进步就会越快。不要像在上个千年一样编程C++。

关于c++ - 解决此错误时出现问题。我正在努力在主函数中传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62168814/

相关文章:

c++ - 为什么我使用这些 C++ 函数会得到 EXC_BAD_ACCESS?

c++ - 为什么我应该更喜欢对智能指针的引用而不是智能指针作为 C++ 中的参数

c - 如何使用 C 中的 for 循环检查数组中的所有元素是否等于特定数字

r - 按矩阵中的行获取所有可能的组合

c - 将大方阵乘以转置比大方阵相乘慢...如何解决?

javascript - 将任意 Javascript 数据对象传递给 Node.js C++ 插件

c++ - 使用 const char * literal 作为 std::map 键是否安全?

C++ 为什么 LLONG_MIN == -LLONG_MIN

c++ 解决方案在 leetcode 上失败,地址未对齐错误,但在 Visual Studio 中运行

c - 返回指向c中指针的指针