1

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?

3 Answers 3

1

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.

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

Comments

1

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.

1 Comment

well, some compilers support this, but it is definitely an extension (see stackoverflow.com/questions/1204521/dynamic-array-in-stack)
0

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);

Comments

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.