This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Static intialization of flexible arrays in C++


Hi Nitin,

>Static initializations of a flexible array works with gcc but not with g++ . is this by design?

Yes, this is by design. C++ does not have flexible arrays (or what I've heard called "stretchy arrays" or "stretchy buffers"). C++ has STL std::vector.

The stretchy buffer is a bad trick -- it's not portable, and may cause certain optimizations to fail is a bad way.

(I'm not sure if it is even legit C code. Maybe it is with C99. I dunno.)

A suggestion is to do the reverse: specify the structure with the array given the maximum length, and allow allocations of less-than-maximum when used off the heap. (There are caveats with this approach as well.)

struct flex_array_1000
{
  int A;
  int Data[1000];
};

Alternatively, you can use template structs to provide more exacting "hard-coded" arrays.

template <int Count>
struct flex_array
{
  int A;
  int Data[Count];
};

...and you can have the struct derived from a common base class if you need some sort of polymorphism.

HTH,
--Eljay



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]