在C++中传递和返回 2D 数组
Passing and returning 2d arrays in C++
所以我是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++中,数组是非常特殊的收集工具。你绝对应该阅读更多关于标准容器类的信息,然后从头开始编写所有新内容 - 相信我,这将节省时间!:)
标准容器类的对象可以通过与基元类型(如int
或double
)相同的简单方式从函数返回。
std::vector<std::vector<int> > GetInts()
{
// ...
return v;
}
你的问题只会消失。
指针和数组意味着低级内存管理;这当然不是初学者的东西!
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- C++ & Python:传递并返回从 python 到 c++ 的 2D 双指针数组
- 返回 2D 数组(在 C# 和 C++ 中)
- 将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
- 函数可以返回 2D 数组吗?
- 在 C++ 中返回 2D arrray
- 从类返回 2D 数组指针
- 分割故障在C 中返回2D矢量时
- 使用类型转换在 C++ 中返回 2D 数组
- C++ - 通过函数返回 2D 数组
- 在C++中传递和返回 2D 数组
- C++函数不返回 2D 数组
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 如何在C++中返回 2D 字符串数组/矢量
- 从C++返回2d数组
- 如何调用对象/构造函数来返回2D数组
- 返回 2D 数组的 C++ "no matching function error"
- 在c++中传递并返回2D阵列
- 需要帮助返回2D数组C++