On Tue, Jan 31, 2012 at 07:50:26PM +0000, Alexander Nasonov wrote: > Joerg Sonnenberger wrote: > > On Tue, Jan 31, 2012 at 07:32:52PM +0000, Alexander Nasonov wrote: > > > #define sizeof_fam(s, m, n) (sizeof(s) + sizeof(((s *)NULL)->m[0]) * (n)) > > > > That's still not necessarily optimal, depending on the padding rules of > > the platform. You want to do offsetof(s, m[0]) + n * sizeof((s*)NULL->m[0]). > > I'm aware of this but I was merely following examples from the standard. > > More specifically I was following DR 282 (flexible array members & > struct padding) which was incorporated into TC2. > > http://std.dkuug.dk/jtc1/sc22/wg14/www/docs/dr_282.htm > > I can add a comment about padding to sizeof_fam. If there is no padding, > my and your expression should return same values.
And if there is padding, and it is after the last field (and a few other clauses) your scheme will allocate a longer buffer than needed. The advantage of Joerg's is that you don't have to 'know' the type of the member. Sudden barin explosion - how about (untested): #define sizeof_var_struct(s, m, c) \ offsetof(s, m[0]) + (c) * (offsetof(s, m[1]) - offsetof(s, m[0])) David -- David Laight: da...@l8s.co.uk