그래서 저는 C++을 처음 접했고이 C++ 코드를 작성했습니다.C++에서 2 차원 배열 전달 및 반환
#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]'
나는 어떤 해결책을 찾기 위해 노력했지만 운. :(
는
코드 업데이트 - 일부 다른 오류 !! :(OP를 확인하십시오. – rnbcoder
'mat_pow'가 돌아 오면'mat1'이 사라지기 때문에 포인터를 반환하는 것은 아무 의미가 없습니다. 포인터를 반환하려면 누가 그 포인터를 할당 할 책임이 있는지 결정해야합니다 메모리를 할당 할 책임이있다.이 경우 포인터를 반환하는 대신 호출자가 포인터를 응답하려는 곳으로 전달해야한다. (또는 이러한 C 유형 대신 실제 C++ 유형을 사용한다. .) –