Path: utzoo!attcan!uunet!husc6!mailrus!ncar!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Something new for C? Keywords: offset of vars within structures Message-ID: <14487@mimsy.UUCP> Date: 11 Nov 88 02:33:15 GMT References: <73@dsoft.UUCP> <2865@ingr.UUCP> <399@babbage.acc.virginia.edu> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 31 >>#define offset(type,field) ((unsigned int)&((type *)0)->field) In article <399@babbage.acc.virginia.edu> mac3n@babbage.acc.virginia.edu (Alex Colvin) writes: >This works by casting a pointer to an unsigned. That sometimes isn't a >good idea. To make integers out of pointers, it's best to subtract. > >#define offset(type,field) ((void *)&((type *)0)->field - (void *)((type *)0)) The advice above is reasonable; the implementation is not. You may not perform arithmetic on pointers to void. This is considered a feature. The dpANS provides a (compiler-dependent!) macro called `offsetof' that might be defined as #define offsetof(t, f) ((char *)&((t *)0)->f - (char *)(t *)0) or more simply as #define offsetof(t, f) ((int)&((t *)0)->f) or as some horrible internal compiler reference: #define offsetof(t, f) __C_compiler_internal_label__offset_of(t, f) Various restrictions in the dpANS make all of these definitions suspect-at-best, but one (whatever it might be) is to be provided and called `offsetof'. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris