Newsgroups: comp.lang.c
Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!sdd.hp.com!elroy.jpl.nasa.gov!thyme!kaleb
From: kaleb@thyme.jpl.nasa.gov (Kaleb Keithley)
Subject: Re: finding offset of a member in C structures
Message-ID: <1991May20.212338.24349@thyme.jpl.nasa.gov>
Organization: Jet Propulsion Laboratory, Pasadena, CA
References: <1276@unisql.UUCP> <16194@smoke.brl.mil>
Date: Mon, 20 May 91 21:23:38 GMT

In article <16194@smoke.brl.mil> gwyn@smoke.brl.mil (Doug Gwyn) writes:
>In article <1276@unisql.UUCP> pckim@unisql.UUCP (Pyung-Chul Kim) writes:
>-	struct a_struct {
>-		short	member1;
>-		char	member2;
>-		int	memner3;
>-	};
>-can I get the offset of member2 at *compiling time* and *portably* ?
>
>Yes, but you shouldn't very often need to do so.

Opinion or Fact?

>-It is possible to provide a compiler operator:
>-	offsetof(member_name,structure_type_name)
>-as it provides 'sizeof' operator.
>-Do you know if there is a compiler operator like above, or is there any
>-alternative solution.
>
>Standard C provides an offsetof() macro, but you don't really need one.
>	struct a_struct foo;
>	int offset2 = (char *)&foo.member2 - (char *)&foo; /* for example */

Here's how *they* do in the X Window System.  I expect it's about as
portable as anything gets.  This is lifted straight from Intrinsic.h.
And BTW, they use it often.

#if defined(CRAY) || defined(__arm)
#ifdef CRAY2

#define XtOffset(p_type,field) \
    (sizeof(int)*((unsigned int)&(((p_type)NULL)->field)))

#else   /* !CRAY2 */

#define XtOffset(p_type,field) ((unsigned int)&(((p_type)NULL)->field))

#endif  /* !CRAY2 */
#else   /* ! (CRAY || __arm) */

#define XtOffset(p_type,field) \
    ((Cardinal) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL)))

#endif /* !CRAY */

#define XtOffsetOf(s_type,field) XtOffset(s_type*,field)

#ifdef notdef
/* this doesn't work on picky compilers */
#define XtOffset(p_type,field)  ((unsigned int)&(((p_type)NULL)->field))
#endif


-- 
Kaleb Keithley                        kaleb@thyme.jpl.nasa.gov

Meep Meep                             Roadrunner
Veep veep                             Quayle
