c++ - 在 C++ 中传递和返回二维数组

标签 c++ arrays multidimensional-array

所以我是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] ...

关于c++ - 在 C++ 中传递和返回二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957705/

相关文章:

c++ - 如何在XCB中隐藏光标?

c# - 导入 C++ dll 时出现问题

c - 使用指针作为数组?

arrays - 尝试用 Argo 解码数组

javascript - 如何在 JavaScript 中将 object.key 添加到现有数组?

algorithm - 将网格(二维阵列)分成随机形状的部分?

c - 指向二维数组元素的指针。我怎样才能将它传递给函数?

c++取消引用通过引用传递分配的指针,给出随机值

C++ 编写解释器 - 确定 break 语句的循环 objective-c ++

c++ - 如何确保仅在 C++ 中提供时才使用特定的类功能?