在C++中传递和返回 2D 数组

Passing and returning 2d arrays in C++

本文关键字:返回 2D 数组 C++      更新时间:2023-10-16

所以我是c++的新手,我写了这段c ++代码。

#include <iostream>
using namespace std;
int** mat_mult(int mat1[2][2], int mat2[2][2]){
    int mat3[2][2] = {{0,0},{0,0}};
    for(int i(0);i<2;i++){
        for(int j(0);j<2;j++){
            for(int k(0);k<2;k++){
                mat3[i][j] += mat1[i][k]*mat2[k][j];
            }
        }
    }
    return mat3;
}
int** mat_pow(int mat[2][2], int n){
    int mat1[2][2] = {{1,0},{0,1}};
    while(n){
        if(n%2==1){
            mat1 = mat_mult(mat, mat1);
        }
        mat = mat_mult(mat,mat);
        n >>= 1;
    }
    return mat1;
}
int specialFib(int n){
    int mat[2][2] = {{0,1},{2,1}};
    mat = mat_pow(mat,n);
    return (mat[0][0]*2 + mat[0][1]);
}
int main(){
    cout << specialFib(3) << endl;
    return 0;
}

但是编译这个给了我这个错误,

prog.cpp: In function 'int** mat_mult(int (*)[2], int (*)[2])':
prog.cpp:13: error: cannot convert 'int (*)[2]' to 'int**' in return
prog.cpp: In function 'int** mat_pow(int (*)[2], int)':
prog.cpp:20: error: incompatible types in assignment of 'int**' to 'int [2][2]'
prog.cpp:22: error: cannot convert 'int**' to 'int (*)[2]' in assignment
prog.cpp:25: error: cannot convert 'int (*)[2]' to 'int**' in return
prog.cpp: In function 'int specialFib(int)':
prog.cpp:30: error: incompatible types in assignment of 'int**' to 'int [2][2]'

我试图找到任何解决方案,但没有运气。 :(

int **mat3 = {{0,0},{0,0}};

这使mat3成为指向整数的指针。您可以将其初始化为指向所需整数的指针的任何指针。但{{0,0},{0,0}}是一个数组,而不是指向整数的指针。

也许你想要:

int mat3[2][2] ...

如果要动态分配 2d 数组,则代码应如下所示:

int** mat3 = new int*[2];
for(int i = 0; i < 2; ++i)
  mat3[i] = new int[2];

然后解除分配:

for(int i = 0; i < 2; ++i) {
    delete [] mat3[i];
}
delete [] mat3;

此外,您必须手动初始化其值


与其他答案一样,我永远不会使用这样的动态数组,而是向量的向量

你标记了这个问题C++所以使用C++!如果您在编译时知道两种大小,则可以使用 std::array<std::array<int,Xsize>, Ysixe>>,也可以std::vector<std::vector<int>>其他大小。

在C++中,数组是非常特殊的收集工具。你绝对应该阅读更多关于标准容器类的信息,然后从头开始编写所有新内容 - 相信我,这将节省时间!:)

标准容器类的对象可以通过与基元类型(如intdouble)相同的简单方式从函数返回。

std::vector<std::vector<int> > GetInts()
{
   // ...
   return v;
}

你的问题只会消失。

指针和数组意味着低级内存管理;这当然不是初学者的东西!