I want to pass a dynamically sized 2D array as a parameter to a function. I know this question has been discussed multiple times in many places but even after applying all permutations and combinations of [] and *, I haven't been able to get this to work.
#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;
}
The error occurs in the line indicated.
If I change the function definition to-
int bestpath(int *A[], int N, int x, int y)
The error comes in the function calling: cannot convert int* to int**. I want to get my basics clear of using *A, *A[], **A, and any other way in which we pass the matrix. And is there any other, better way to do this?
A[N][N]is anint(you access the element). The address of that is aint *.int A[N][N];uses variable length arrays which are a GCC extension.&A[N][N](withAdeclared asint A[N][N]) is undefined behaviour.