Reputation: 1486
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?
Upvotes: 2
Views: 6058
Reputation: 206566
Simply call the function as:
int ans= bestpath(A, N, 0, 0);
And change your function declaration to:
int bestpath(int A[N][N], int x, int x, int y);
You do need to move around code to get it to compile further through, here is the online sample.
Upvotes: 1