structure element offsets

Wayne Throop throopw at dg_rtp.UUCP
Tue Dec 2 02:13:54 AEST 1986


> stuart at bms-at.UUCP (Stuart D. Gathman)
>> bader at spice.cs.cmu.edu (Miles Bader)

>> Is there any way of finding the offset of a structure element from
>> the beginning of a structure in a portable AND efficient way?
> #define spos(s,m)	((char *)&((struct s *)0)->m - (char *)0)
> #define sposa(s,m)	((char *)((struct s *)0)->m - (char *)0)
> #define slen(s,m)	(sizeof((struct s *)0)->m)
> #define smp(s,m,p)	((struct s *)(p-&((struct s *)0)->m))
> #define smpa(s,m,p)	((struct s *)(p-((struct s *)0)->m))

Stuart's solutions perhaps come closest to satisfying the original
question, but a couple of points remain.  First, there is no guarantee
that pointer arithmetic or offset calculations will work for the null
pointer.  Second, the notion of "offset" is ill defined in the original
question.  Stuart's solution provides the offset in char-sized units,
and this is probably what Miles meant, but it is well to remember that
the notion offset-of-struct-member-in-char-sized-chunks is probably
not something that "ought" to be floating around in code meant to be
portable or maintainable.

The way the question was originally put (requiring a portable solution),
the only way to do it (assuming that offset-in-sizeof-sized-chunks is
wanted) is to create an instance of the structure at a non-nil address
(eg, create an external struct of the required type) and do the offset
calculation as Stuart does above, but with the actual structure.

--
Sometimes I think the only universal in the computing field is the
fetch-execute cycle.
                                --- Alan J. Perlis
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list