Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!lll-crg!ames!amdahl!rtech!daveb From: daveb@rtech.UUCP Newsgroups: comp.lang.c Subject: Re: structure element offsets Message-ID: <510@rtech.UUCP> Date: Wed, 26-Nov-86 12:50:14 EST Article-I.D.: rtech.510 Posted: Wed Nov 26 12:50:14 1986 Date-Received: Fri, 28-Nov-86 02:01:04 EST References: <1096@spice.cs.cmu.edu> <768@nike.UUCP> Reply-To: daveb@rtech.UUCP (Dave Brower) Organization: Relational Technology, Alameda CA Lines: 24 Keywords: In article <768@nike.UUCP> hahn@ames-nas.arpa (Jonathan Hahn) writes: >In article <1096@spice.cs.cmu.edu> bader@spice.cs.cmu.edu (Miles Bader) asks: >>Is there any way of finding the offset of a structure element from >>the beginning of a structure in a portable AND efficient way? > >Try: > >#define OFFSET(elem, type) (&(((type *)0)->elem)) > >This utilizes a pointer of address 0, for which the address of the >element reference yeilds the offset of the element. Efficient, yes. Portable, no. There are numerous compilers that choke on these expressions. One can argue that those aren't "real C compilers", but the real question is, "Do you really need to do this?" Sometimes compiler holes are God's way of saying you're doing something inadvisable. You will have be tricky, obfuscated, type-incorrect code, with gobs of casting back and forth with ptrs to manipulate the elements. Having dealt with this sort of code, I suggest you seek another approach to the problem -- "that way lies madness". -dB -- {amdahl, sun, mtxinu, cbosgd}!rtech!daveb