Question

Why does not this code compile with VC++ 15 in visual studio 2008?

Errors: C2057: expected constant expression, C2466: cannot allocate an array of constant size 0.

void foo(int a, int b)
{
double arr[a][b]
...
}

Although it works fine in GCC 4.4. I need compatibility between compilers.

Was it helpful?

Solution

Why does not this code compile with VC++ 15 in visual studio 2008?

Because C-style variable length arrays are not part of the C++ language. GCC provides them as a non-standard extension; some compilers don't.

I need compatibility between compilers.

Then you'll need a dynamic array, for example:

std::vector< std::vector<double> > arr(a, std::vector<double>(b));

or, if you want all the elements to be contiguous as they would be in a 2-dimensional array:

std::vector<double> arr(a*b);

with appropriate arithmetic to calculate the indexes when you access it.

OTHER TIPS

The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory and the vectors are best choice for this kind of operations.

For more information refer

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top