Re: Static intialization of flexible arrays in C++

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux