finding offset of a member in C structures
Douglas M Jaffe
dmj at cunixa.cc.columbia.edu
Sat May 25 15:46:08 AEST 1991
In article <1991May20.201857.635 at lynx.CS.ORST.EDU> osbornk at mist.CS.ORST.EDU (Kasey S. Osborn) writes:
>In article <16194 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
>|In article <1276 at unisql.UUCP> pckim at unisql.UUCP (Pyung-Chul Kim) writes:
>|-struct a_struct {
>|-short member1;
>|-char member2;
>|-int member3;
>|-};
>|-can I get the offset of member2 at *compiling time* and *portably* ?
>|
>|Yes, but you shouldn't very often need to do so.
>|
>|-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 */
>
>Really? I can't find a reference to offsetof() in any of my C references.
>In fact, GNU CC does not preprocess offsetof() and instead treats it as an
>external reference. Are you sure this is standard?
>
>What compiler are you using? What is the syntax of offsetof()? I've
>been trying to find a palatable solution to this problem with no luck.
i have to check my ansi reference for offsetof(). however, i wouldn't
rely on the assumption that offsetof() will exist in every
__STDC__ (stupid c) compiler that you encounter. you might want
to consider adding the following macros to your bag of tricks.
these offset macros should work in almost _every_ c compiler/interpreter that
exists: from msc, turboc, SunOS cc, rs/6000 xlc, to tandem (yes, tandem) c.
NOTES
-----
1. i wrote these many years ago, on a buggy ibm-pc (yes, p. c. !) compiler.
2. because of #1, i had to code like a prude, with parens all over.
3. these macros have been working ever since.
4. don't flame me on the parameter names that i used!
======================================================================
#define FAKE_ADDR ((char *) 256)
/* offset to start of field */
#define OFFSET_TO(tttt,mmmm) \
(((unsigned long) (&(((tttt *)(FAKE_ADDR))->mmmm) )) - \
((unsigned long) ((tttt *)(FAKE_ADDR))))
/* size from start of struct to end of mentioned member */
#define SIZE_TOEND(t,m) \
(OFFSET_TO(t,m) + sizeof(((t *)(FAKE_ADDR))->m))
/* offset of last byte of mentioned member from start of struct */
#define OFFSET_TOEND(t,m) (SIZE_TOEND(t,m) - (unsigned long)1)
----------------------------------------------------------------------
_
,---------'_)
(_/\ O O /
\ v /
\___/
U
"doggie fresh"
More information about the Comp.lang.c
mailing list