I have a simple function in which an array is declared with size depending on the parameter which is int.
void f(int n){ char a[n]; }; int main() { return 0; }
This piece of code compiles fine on GNU C++, but not on MSVC 2005.
I get the following compilation errors:
.\main.cpp(4) : error C2057: expected constant expression .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0 .\main.cpp(4) : error C2133: 'a' : unknown size
What can I do to correct this?
(I’m interested in making this work with MSVC,without using new/delete)
What you have found it one of the Gnu compiler’s extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression.
There was a feature added to C in the 1999 update to that language called variable length arrays, where this is legal. If you can find a C compiler that supports C99, which is not easy. But this feature is not part of standard C++, not is it going to be added in the next update to the C++ standard.
There are two solutions in C++. The first is to use a std::vector, the second is just to use operator
new []:While I was writing my answer, another one posted a suggestion to use _alloca. I would strongly recommend against that. You would just be exchanging one non-standard, non-portable method for another one just as compiler-specific.