Xref: utzoo comp.lang.c:13998 comp.lang.c++:1940 Path: utzoo!utgpu!watmath!clyde!att!ucbvax!ernie.Berkeley.EDU!jas From: jas@ernie.Berkeley.EDU (Jim Shankland) Newsgroups: comp.lang.c,comp.lang.c++ Subject: offsetof (was: Re: Something new for C?) Keywords: offset of vars within structures Message-ID: <26740@ucbvax.BERKELEY.EDU> Date: 9 Nov 88 16:54:40 GMT References: <73@dsoft.UUCP> <481@njsmu.UUCP> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: jas@ernie.Berkeley.EDU (Jim Shankland) Organization: University of California, Berkeley Lines: 26 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