4

I have ported some code from Mingw which i wrote using code::blocks, to visual studio and their compiler, it has picked up many errors that my array sizes must be constant! Why does VS need a constant size and mingw does not?

e.g.

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

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

The only way i can think to get around this is....

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

Will i have to change everything to dynamic or is there another way in VS?

Kaije
  • 2,631
  • 6
  • 38
  • 40
  • 4
    Ah ok, so mingw has been fooling me into thinking its actually valid c++ code! but it isn't, would be useful to be able to do it though... – Kaije Aug 14 '10 at 14:11

3 Answers3

5

Why does VS need a constant size and mingw does not?

Because Variable Length Arrays are not a part of C++ although MinGW(g++) supports them as extension. Array size has to be a constant expression in C++.

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

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
4

The only way i can think to 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);

P.S. Also, I don't think that using hungarian notation in C++ code is a good idea.

SigTerm
  • 26,089
  • 6
  • 66
  • 115
  • it just so happens my example is using an char string, i use arrays of integers and classes too :P and plus i'm doing windows programming, so i prefere using null terminating strings so that i can pass them to the windows api functions/calls, and i think the .c_str() member of std::string is constant, so i can't always pass it to windows functions. – Kaije Aug 14 '10 at 14:00
  • 1
    @kaije: If you want to pass the buffer to windows functions for writing, a vector still automates memory management and `&vec[0]` gives you the pointer to the buffer. If you want to avoid dynamic allocation, then use various constants like `MAX_PATH` that windows defines etc. – UncleBens Aug 14 '10 at 14:47
  • @kaijethegreat: There's never a reason to put yourself in a position where you need to manually free something. Use a container that will do it for you, all the time. – GManNickG Aug 14 '10 at 19:14
0

Use _alloca to allocate variable amounts off the stack, then write an encapsulating class. It's a litlte messy, but you CAN write your own variable length stack-based arrays.

Puppy
  • 144,682
  • 38
  • 256
  • 465