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: Nitin Karkhanis <nkarkhan at yahoo dot com>
- To: Eljay Love-Jensen <eljay at adobe dot com>, gcc-help at gcc dot gnu dot org
- Date: Sun, 13 Feb 2005 10:18:10 -0800 (PST)
- Subject: Re: Static intialization of flexible arrays in C++
Thank you for your email.
Flexible arrays are indeed legal.
http://gcc.gnu.org/onlinedocs/gcc-3.4.3/gcc/Zero-Length.html#Zero-Length
(and it really is not a hack or a bad trick :), it has
been used for ages and I would be hard-pressed to come
up with an equally elegant solution to represent
variable size arrays )
The trick of using the max array size is not workable
in embedded applications where memory is at a premium.
And then there is the static intialization problem.
e.g
typedef struct {
} a_t;
I thought C++ is a superset of C and C code should
compile in a C++ compiler (except for strict type
checking) ..but guess not.
N.
--- Eljay Love-Jensen <eljay@adobe.com> wrote:
> 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
>
>
__________________________________
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
http://mobile.yahoo.com/maildemo