Consider following code:

struct Foo{
    std::string val;
int n = 5;
Foo a[n];
const size_t m =10;
Foo b[m];

Even a variable length array (VLA) is declared, the program compiles using g++ -std=c++0x. VLA is not an official part of C++11 [1]. Clang supports such variable length arrays in very limited circumstances [2], that is :

- The element type of a variable length array must be a POD ("plain old data") type, which means that it cannot have any user-declared constructors or destructors, any base classes, or any members of non-POD type. All C types are POD types.

- Variable length arrays cannot be used as the type of a non-type template parameter.

Hence, above code does not compile using clang, an Error of variable length array of non-POD element type will be given. For a variable length array, using STL vector is a good option.

If you really want to use array, an alternative solution is mentioned in [3]: use a dynamically allocated array instead:

struct Foo{
    std::string val;
int n = 5;
Foo *a = new Foo[n];
delete [] a;
a = NULL; // clear to prevent using invalid memory reference (dangling pointer)

In practice, as mentioned by Scott Meyers in “Effective STL”, vector and string are preferred to dynamically allocated arrays.


  1. Does C++ support Variable Length Arrays?

  2. Clang: Language Compatibility

  3. Error: Variable length array of Non-POD element type ‘string’

  4. Wikipedia: Dangling Pointer

Yang Song

Ph.D. Student in Robotics