Why not dynamic char array sizing
Just wondering about creating a dynamic string array
int i = this->txtMain->Text->Length - 1;
char x[i];
This gives me 3 errors
Error 1 error C2057: expected constant expression
Error 2 error C2466: cannot allocate an array of constant size 0
Error 3 error C2133: 'x' : unknown size
Can someone explain to me why. Im a n00b
Thanks :)
Re: Why not dynamic char array sizing
char x will be placed on the function stack, and this is determent at compile time. In other words, the compiler needs to know how many 'i' is while it is compiling the code, and because 'i' is determent at runtime, you get this error. 'i' needs to be a static number at compile time.
Re: Why not dynamic char array sizing
C++ doesn't support variable length arrays.
You have to dynamically allocate the array
e.g.
Code:
int i = this->txtMain->Text->Length - 1;
char *x = new char[i];
....
delete [] x;
It's better to use std::string.
Kurt
Re: Why not dynamic char array sizing
And it's a tad on the controversial side.
It seems that in C99 (not C++) this is a supported concept.
We'd have to consult any notes on commentary related to the committee's that approve the changes to these languages to really understand why.
This wasn't a concept supported in older C standards, back when C++ was developed by incorporating C.
When C99 incorporated it, the C++ standards committee had already met over C++98, as I recall, and the two different languages have further diverged since.
Obviously any technical reasons for not supporting a dynamic sized local array of this kind are surmountable arguments, otherwise C99 wouldn't have incorporated it.
However, for C++ we have alternatives - strings, vectors and such, which according to the philosophies governing these decisions meant the chance of C++ accepting this change was lessened at the time.
I seem to recall that a few C++ compilers might even allow this as an extension, but it isn't portable if you did find it compiles.
It's also not quite as safe, which is another reason not to use it and instead favor vectors or strings for this purpose.