C++ 错误:无效类型';int[int]';数组下标
我想将动态大小的2D数组作为参数传递给函数。我知道这个问题已经在很多地方讨论过多次,但即使在应用了[]和*的所有排列和组合之后,我仍然无法让它起作用C++ 错误:无效类型';int[int]';数组下标,c++,arrays,function,dynamic,syntax,C++,Arrays,Function,Dynamic,Syntax,我想将动态大小的2D数组作为参数传递给函数。我知道这个问题已经在很多地方讨论过多次,但即使在应用了[]和*的所有排列和组合之后,我仍然无法让它起作用 #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
#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*转换为int**。
我想让我的基本知识清楚地知道如何使用*A、*A[]、**A以及传递矩阵的任何其他方式。
还有其他更好的方法吗?只需将函数调用为:
int ans= bestpath(A, N, 0, 0);
并将函数声明更改为:
int bestpath(int A[N][N], int x, int x, int y);
您确实需要移动代码以使其进一步编译,以下是。
A[N][N]
是一个int
(您可以访问该元素)。它的地址是aint*
inta[N][N]
使用作为GCC扩展的可变长度数组。除了@sftrabbit所说的之外,即使您可能有一个在运行时指定了维度的数组,&a[N][N]
(其中a
声明为int a[N][N]
)是未定义的行为。但我需要用户输入N。@poonamkohli:然后使用std::vector
,这就是std::vector
的用途。可变长度数组不是标准的一部分,您的代码可能无法移植到某些不支持它们的编译器。
int bestpath(int A[N][N], int x, int x, int y);