usertfwr
usertfwr

Reputation: 309

Why is there a compiler error, when declaring an array with size as integer variable?

In visual studio, I have an error that I didn't have before in Dev-C++:

int project = (rand() % 5) + 1 ;
int P[project][3];

Compilation:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'P' : unknown size

Can you help to understand this error?

Upvotes: 1

Views: 901

Answers (3)

MSalters
MSalters

Reputation: 179779

The standard C++ class for variable-length arrays is std::vector. In this case you'd get std::vector<int> P[3]; P[0].resize(project); P[1].resize(project); P[2].resize(project);

Upvotes: 0

Mert Akcakaya
Mert Akcakaya

Reputation: 3129

You need to allocate memory dynamically in this case. So you cannot say int P[someVariable]. You need to use int *mem = new int[someVariable]

Have a look at this link.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206508

In C++ you can only create arrays of a size which is compile time constant.
The size of array P needs to be known at compile time and it should be a constant, the compiler warns you of that through the diagnostic messages.

Why different results on different compilers?

Most compilers allow you to create variable length arrays through compiler extensions but it is non standard approved and such usage will make your program non portable across different compiler implementations. This is what you experience.

Upvotes: 1

Related Questions