我想将动态大小的二维数组作为参数传递给函数。我知道这个问题已经在很多地方讨论过多次,但即使在应用 [] 和 * 的所有排列和组合之后,我也无法让它发挥作用。
#include<iostream>
#include<algorithm>
using namespace std;
int bestpath(int *A, int N, int x, int y)
{ if(x>= N || y>=N)
return 0;
if(x == y == N-1)
return 0;
int value= A[x][y]; // Error: Invalid type 'int[int]' for array subscript.
value+= max(bestpath(A, x+1, y, N), bestpath(A, x, y+1, N));
return value;
}
int main()
{ int T, N, i, j, k;
cin>>T;
for(i=0; i<T; i++)
{ cin>>N;
int A[N][N];
for(j=0; j<N; j++)
{ for(k=0; k<N; k++)
{ cin>>A[j][k];
}
}
int ans= bestpath(&A[N][N], N, 0, 0);
cout<<ans<<endl;
}
return 0;
}
错误发生在指示的行中。
如果我将函数定义更改为-
int bestpath(int *A[], int N, int x, int y)
错误来自函数调用:无法将 int* 转换为 int**。 我想了解使用 *A、*A[]、**A 以及我们传递矩阵的任何其他方式的基础知识。 还有其他更好的方法吗?
最佳答案
只需将函数调用为:
int ans= bestpath(A, N, 0, 0);
并将您的函数声明更改为:
int bestpath(int A[N][N], int x, int x, int y);
您确实需要移动代码以使其进一步编译,这里是 online sample .
关于c++ - 错误 : Invalid type 'int[int]' for array subscript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13669993/