0

Here is my code where I am getting error:

#include<bits/stdc++.h>
using namespace std;
int n;
bool is_attacked(int board[][n],int x,int y) //Here I am getting error
{
    for(int i=0;i<n;i++)
    {
        if(board[x][i])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        if(board[i][y])
        return false;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(board[i][j]&&(x+y==i+j||i-j==x-y))
            return false;
        }
    }
    return true;
}

It is giving error in function parameters of is_attacked and the error coming is:

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

Could anyone please tell me what I am doing wrong? Thanks in advance?

  • (1) `n` is uninitialized. (2) While sending 2D array as parameter if not both the indices of the array atleast the second index must be specified and that too a constant. And where is `main()` ? – Aditi Rawat Dec 09 '17 at 16:53
  • @AditiRawat n is global and due to lengthy code I have ignored it –  Dec 09 '17 at 16:55
  • Recommended read: https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function – Aditi Rawat Dec 09 '17 at 17:03
  • Here I want to know what is wrong in my code since I am also providing the column size to the array? –  Dec 09 '17 at 17:05
  • Ok ! so it means the only option I have to use the 2D array is to make it global to escape this error. –  Dec 09 '17 at 17:10

1 Answers1

0

The thing is the parameter you pass as the index of the 2D array needs to be a compile time evaluable constant expression. And since you are inputting n at run-time it is giving you an error.
An alternate method could be you define a macro, say #define MAX 10 and change your function signature to

bool is_attacked(int board[][MAX],int x,int y, int n)

I am assuming this is N-queens or K-knights sort of problem, so you could define the macro accordingly.

Aditi Rawat
  • 784
  • 1
  • 12
  • 15