jas@ernie.Berkeley.EDU (Jim Shankland) (11/10/88)
In article <481@njsmu.UUCP> klg@njsmu.UUCP (Kenneth Goodwin) writes: >Until they actually stick something like [offsetof] into the compiler, try >this: > >#define offsetof(Struct, Member) (&((struct Struct *)0)->Member) > >... > > Since all kludges have an inherent risk of non-portability > comments on the above method are welcome. Alas, I've run into C compilers on a few UNIX machines that barf on this. Not about the syntax itself -- they just don't want you dereferencing the null pointer (even though you're not, really). Which means that for maximal portability, this won't work either. On such machines, you must have an instance of the structure: struct mumble foo; int mem_offset = (char *)(&foo.member) - (char *)(&foo); Sigh. The things you have to put up with in the portability trenches. This is about the 10,000th reason that we need ANSI C *now*. Jim Shankland jas@ernie.berkeley.edu
rbutterworth@watmath.waterloo.edu (Ray Butterworth) (11/16/88)
In article <26740@ucbvax.BERKELEY.EDU>, jas@ernie.Berkeley.EDU (Jim Shankland) writes: > On such machines, you must have an instance of the structure: > struct mumble foo; > int mem_offset = (char *)(&foo.member) - (char *)(&foo); > Sigh. The things you have to put up with in the portability trenches. The same argument applies for the alignof macro: #define alignof(type) /* assumes double is max aligned */ \ ( (char*)&(((struct {double _d; char _c; type _t;}*)0)->_t) \ - (char*)&(((struct {double _d; char _c; type _t;}*)0)->_c) ) which is equally non-portable, but for some reason the Committee chose not to make this macro part of the Standard even though alignof() seems to be more useful (to me at least) than offsetof(). > This is about the 10,000th reason that we need ANSI C *now*. And this is one more reason why "ANSI C now" still isn't good enough.
gwyn@smoke.BRL.MIL (Doug Gwyn ) (11/17/88)
In article <22164@watmath.waterloo.edu> rbutterworth@watmath.waterloo.edu (Ray Butterworth) writes: >... for some reason the Committee chose not to make this macro >part of the Standard even though alignof() seems to be more useful >(to me at least) than offsetof(). As has been explained many times before, and will be explained yet again in the third-round response document, alignment can depend on context, so alignof(type) is not realizable in some implementations. >And this is one more reason why "ANSI C now" still isn't good enough. I think having a standard drafted by people who understand these issues will be a great service to the C community.