问题
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?
回答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.
回答2:
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.
回答3:
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);
来源:https://stackoverflow.com/questions/15471486/why-is-there-a-compiler-error-when-declaring-an-array-with-size-as-integer-vari