Why does VS require a constant array size, but MinGW does not? And is there a way around this?

I ported some code from Mingw, which I wrote using code :: blocks, for the visual studio and their compiler, it took a lot of errors so that the array sizes were constant! Why doesn't VS need a constant size, and mingw doesn't work?

eg.

const int len = (strlen(szPath)-20); char szModiPath[len]; 

the len variable is underlined in red to say its error and says "expected constant expression"

The only way I can get around this is ...

 char* szModiPath = new char[len]; delete[] szModiPath; 

Do I need to change everything to dynamic or is there any other way in VS?

+4
source share
3 answers

Why does VS need a constant size, but mingw does not?

Since variable length arrays are not part of C ++, although MinGW (g ++) supports them as an extension. The size of the array must be a constant expression in C ++.

In C ++, it is always recommended to use std::vector instead of C-style arrays . :)

+5
source

The only way I can get around this is ...

This is not the only way. Use STL containers.

 #include <string> .... std::string s; s.resize(len); 

or

 #include <vector> .... std::vector<char> buffer(len); 

PS Also, I do not think that using Hungarian notation in C ++ code is a good idea.

+6
source

Use _alloca to extract variable amounts from the stack, and then write an encapsulating class. This is inconvenient, but you CAN write your own variable-stack stack arrays.

0
source

All Articles