2

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?

3
  • A[N][N] is an int (you access the element). The address of that is a int *. Commented Dec 2, 2012 at 14:05
  • 1
    int A[N][N]; uses variable length arrays which are a GCC extension. Commented Dec 2, 2012 at 14:06
  • In addition to what @sftrabbit said, even if you possibly could have an array whose dimensions are specified at run-time, &A[N][N] (with A declared as int A[N][N]) is undefined behaviour. Commented Dec 3, 2012 at 14:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But I need the user to enter N.
@poonamkohli: Then use a std::vector, that is what std::vector is for. Variable length arrays are not part of the standard and your code may not be portable to some compiler which does not support them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.