From 4734985271937811505
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,855073145fb9fdb7
X-Google-Attributes: gidf78e5,public
From: ncm@nospam.cantrip.org (Nathan Myers)
Subject: Re: Minimum Size of Array in Standard (solution)
Date: 1998/11/05
Message-ID: <71p6m5$4m1$1@shell7.ba.best.com>#1/1
X-Deja-AN: 408605702
Approved: Fergus Henderson <fjh@cs.mu.oz.au>
References: <199811032027.NAA25799@ncar.ucar.EDU>
X-Original-Date: 4 Nov 1998 01:27:33 -0800
X-Complaints-To: news@news.unimelb.edu.au
X-Trace: izvestia.its.unimelb.edu.au 910257179 16275 128.250.29.17 (5 Nov 1998 09:12:59 GMT)
Organization: http://www.cantrip.org/
X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUANkFsC+EDnX0m9pzZAQG7nQF/Xc1etDNobxz3udqtuJgd5QpxQ+8lMPPq SPfuH90gzuH53S6jOktPcd9kM9qyRic4 =Fdfe
NNTP-Posting-Date: 5 Nov 1998 09:12:59 GMT
Newsgroups: comp.std.c++

>> "Jim Cobban" <Jim.Cobban.jcobban@nt.com> writes:
>> ...
>> |>  This is used in a lot of existing code to
>> |>  represent an array whose size is known by some implementation specific
>> |>  method, for example in a structure such as the following:
>> |>  
>> |>   struct varstruct
>> |>   {
>> |>     unsigned int	num_elements;
>> |>     int		elements[0];
>> |>   };
>> 
>> This code is illegal (in C).

There is a standard-conforming way to get a similar effect.

  template <class T>
    struct varstruct 
  {
    union {
      unsigned int num_elements;
      T dummy[(sizeof(unsigned int)+sizeof(T)-1)/sizeof(T)];
    };
    T* elements() { return (T*)(char*)(this+1); }
  };

The dummy array ensures that (this+1) is aligned properly for a T.
If you have more data members than just num_elements, you can put 
them in a struct and use that in the sizeof expression in place of 
unsigned int.

Of course you have to make sure there is usable storage at this[1].

-- 
Nathan Myers
ncm@nospam.cantrip.org  http://www.cantrip.org/
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]



