randomUser
randomUser

Reputation: 693

Why am I getting array bound is not an integer constant before ‘]’ token even though declared the size globally?

I was trying topological sorting but I got error with the declaration of array.I had attached the part in which i got error. If I replace the n in visited array with the value 6 then the algorithm work fine . I do not understand why this is happening? Here is the Code in which I was getting error: Code On Ideone

#include<iostream>
#include<vector>
using namespace std;

int n=6;
int visited[n]={0};
int main()
{
    cout<<visited[0];
}

Upvotes: 2

Views: 1394

Answers (3)

Aziuth
Aziuth

Reputation: 3902

While the other answers are correct in telling you what the problem is, they miss out on giving you an actual way to declare dynamic arrays.
From the topic being "topological sorting", I assume that you only were testing when you declared your variable n and that it might be an actual variable (rather than a constant) later.

If so, please have a look at How to create a dynamic array of integers.

In short: You can create a pointer that points to the start of an array on the heap:

int* visited = new int[n];

which works just like you are used to with arrays, but must be freed with delete in order to avoid leaking memory.

Better is using a container class that does this for you:

std::vector<int> visited(n);

Put any line in your code and it will work as intended.
As a general recommendation, you should read tutorials on how to work with the STL, including getting an overview over its container classes.

Upvotes: 1

salchint
salchint

Reputation: 391

Defining an array this way means you want its memory to have static duration, because it is a global variable. In addition you intend to use a C-like array. The type-system of C++ works in a way that visited is, in the working situation, of type int[6]!! I.e. the number of elements is part of the type. Hence this information needs to be first, available at compile time and second, be immutable. n of your example can change at any time and is therefore not qualified to be used in the array type.

You can do the following instead:

constexpr unsigned int n {6};
int visited[n]={0};

... or if you also want to initialize the array in a proper way, use this for example:

int visited[]={0, 0, 0, 0, 0, 0};

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

There are two things, in your code

 int visited[n]={0};

However, following the definition of constant-expression in C++, you can do something like

 const int n=6;
 int visited[n]={0};  //not a VLA anymore

Upvotes: 4

Related Questions