Array requires constant; wont accept variable

I don't have any idea where to start looking for this,and have no explanation why it started not working. I have a file with some dynamically sized arrays, ie.
1
2
int i = 3;
char c[i];

but all of a sudden when I try to compile, I get
main.cpp
main.cpp(6) : error C2057: expected constant expression
main.cpp(6) : error C2466: cannot allocate an array of constant size 0
main.cpp(6) : error C2133: 'c' : unknown size


The source file is
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main() {
   int i = 3;
   char c[i];
   cout << "Works!\n";
   cin.get();
   return 0;
}

and the compiler is Microsoft cl.exe, using
cl.exe main.cpp /EHsc
I think when you are creating a static array, and want to pass a variable as the size of the array, the variable must be const.

1
2
const int i = 0;
char c[i];
But this is counterintuitive, considering the variable needs to change

When I originally wrote the file I'm trying to compile, it worked fine, but now it isnt

All that's changed is now I'm using the cmd to compile instead of an IDE (but its still the same compiler)

EDIT: making the variable const does fix this, but the fact remains a) it needs to remain dynamic and b) it used to work :/
Last edited on
If it needs to be non-const, then you need to use dynamic memory allocation. I would just use an std::vector.

It is only valid in C. In C++ you cannot do that (although some compilers will let you anyway).
I don't understand, why is this invalid in c++, yet still usable if one uses an IDE?

If an IDE can do it, why can't I?
In C++ you cannot do that (although some compilers will let you anyway).
The IDE im using uses the same compiler program (im using the compiler straight from the IDE's source)
In that case, I dunno. The compiler might be passing extra arguments that allow that. However, I would discourage you from doing this anyway unless you are specifically trying to use C99.
Generally C++ won't allow that because I think the variable declarations can be re-arranged by the compiler so the translated machine code may not guarantee that i is actually initialized before char c[i].

Compilers can do a bunch of optimizations that happen behind the scenes with one of those being a re-arrangement of line codes.
Update: found that it wasnt working in the IDE, I was using a gcc IDE not VisualStudio (it doesn't work in visual studio). Uncertain what to do, b/c my lib makes use of dynamically sized arrays :/

Any non-messy ways to correct this?
Use std::vector.
Topic archived. No new replies allowed.