Re: Static intialization of flexible arrays in C++

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

 



Nitin,

  What compiler are you using with this code?

  As your link shows, the flexible arrays are only legal in C99, and
their static initialization only legal through GCC extensions.

corey


On Sun, 13 Feb 2005 10:18:10 -0800 (PST), Nitin Karkhanis
<nkarkhan@xxxxxxxxx> wrote:
> 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@xxxxxxxxx> 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
>

[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