Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!husc6!panda!genrad!decvax!mcnc!rti-sel!dg_rtp!throopw From: throopw@dg_rtp.UUCP (Wayne Throop) Newsgroups: comp.lang.c Subject: Re: structure element offsets Message-ID: <720@dg_rtp.UUCP> Date: Mon, 1-Dec-86 11:13:54 EST Article-I.D.: dg_rtp.720 Posted: Mon Dec 1 11:13:54 1986 Date-Received: Tue, 2-Dec-86 03:28:55 EST References: <1096@spice.cs.cmu.edu> <292@bms-at.UUCP> Lines: 33 Summary: not possible, with portable constraint & no instance of struct > stuart@bms-at.UUCP (Stuart D. Gathman) >> bader@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 !mcnc!rti-sel!dg_rtp!throopw