structure element offsets

daveb at rtech.UUCP daveb at rtech.UUCP
Thu Nov 27 03:50:14 AEST 1986


Keywords:

In article <768 at nike.UUCP> hahn at ames-nas.arpa (Jonathan Hahn) writes:
>In article <1096 at spice.cs.cmu.edu> bader at 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



More information about the Comp.lang.c mailing list