This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Static intialization of flexible arrays in C++
- From: Eljay Love-Jensen <eljay at adobe dot com>
- To: Nitin Karkhanis <nkarkhan at yahoo dot com>, gcc-help at gcc dot gnu dot org
- Date: Sun, 13 Feb 2005 11:06:40 -0600
- Subject: Re: Static intialization of flexible arrays in C++
- References: <20050212020018.93765.qmail@web30810.mail.mud.yahoo.com>
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