-2

I am getting this error while running the code:

[Error] array bound is not an integer constant before ']' token

Here is a segment of the code:

using namespace std;
int R,C;
bool isSafer(int grid[][C],int row,int col, bool visited[][C])
{
    if(row<R && row>=0 && col<C && col>=0 && grid[row][col] && visited[row][col])
    {
        return true;
    }
    return false;
}
int main()
{
  ....
  ....
  cin>>R>>C;
  int grid[R][C];
  ....

}

In int main() I ask user for the input for R and C. I have also declared the array in the main function and called in in the above mentioned function. Please suggest me how should I pass my array to the function with the parameter as variable taken by the user.

Ayush Goyal
  • 57
  • 1
  • 10
  • 3
    Possible duplicate of [Passing a 2D array to a C++ function](http://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function) – Baruch Nov 22 '15 at 08:29

1 Answers1

1

There is no variable-length arrays in C++. It means, following code

int w, h;
std::cin >> w >> h;
int a[w][h];

is illegal. If it works for you, it's because your compiler supports it as an extension (as an additional feature that is not part of standard C++). Other compilers may not support it. Even if it works for you, there is no way you can pass it to function.

There are following soltions:

  • Use nested std::vector. It's easy, but it may be slightly slow and/or memory-expensive for 2D arrays.
  • Convert 2D array to 1D array of ints and pass width separately. Best solution in my opinion.
  • Use 1D array of pointers to new-allocated 1D arrays of ints. And pass it as int **param.
  • If you only need to change one dimension of the array, you can do something like
    constexpr int w = 5; int *a[w] = new int[h][w];
    This won't work if you need to change both dimensions.
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • I have already declared the array in my main function and calling it in the above function. By variable size I meant that some previous suggestion were to declare it something like gird[][5] and similar. In my case the size is not constant. – Ayush Goyal Nov 22 '15 at 08:32
  • @AyushGoyal Sorry, I don't understand your comment. If variable-lenght arrays work for you, then it means that your compiler support them as an extension. Other compilers may not do so. Anyway, you can't do this `int a; void f(int param[][a]).` There is no way you can pass your array to function. You should use one of the solutions from my answer. – HolyBlackCat Nov 22 '15 at 08:40
  • Could you suggest me how can I possibly proceed? I don't know the parameters for the array which I need to ask from user. Then that sized array is used for further manipulation. – Ayush Goyal Nov 22 '15 at 08:46
  • @AyushGoyal I've already written possible solutions in my answer. – HolyBlackCat Nov 22 '15 at 08:49
  • Thanks. I will try them out. – Ayush Goyal Nov 22 '15 at 08:50