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?

iammilind
  • 68,093
  • 33
  • 169
  • 336
usertfwr
  • 309
  • 1
  • 6
  • 31

3 Answers3

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • well, some compilers support this, but it is definitely an extension (see http://stackoverflow.com/questions/1204521/dynamic-array-in-stack) – Philipp Aumayr Mar 18 '13 at 07:17
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.

Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
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);

MSalters
  • 173,980
  • 10
  • 155
  • 350