Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!lll-crg!rutgers!dayton!viper!dave From: dave@viper.UUCP (David Messer) Newsgroups: comp.lang.c Subject: Re: structure element offsets Message-ID: <386@viper.UUCP> Date: Fri, 28-Nov-86 17:29:47 EST Article-I.D.: viper.386 Posted: Fri Nov 28 17:29:47 1986 Date-Received: Fri, 28-Nov-86 21:16:25 EST References: <1096@spice.cs.cmu.edu> <768@nike.UUCP> <3622@watmath.UUCP> Reply-To: dave@viper.UUCP (David Messer) Organization: Lynx Data Systems, Minneapolis, MN Lines: 31 Keywords: structure, offset In article <3622@watmath.UUCP> rbutterworth@watmath.UUCP (Ray Butterworth) writes: >In article <768@nike.UUCP>, hahn@fred (Jonathan Hahn) writes: >> > Is there any way of finding the offset of a structure element from >> > the beginning of a structure in a portable AND efficient way? >> Try: >> #define OFFSET(elem, type) (&(((type *)0)->elem)) >> This utilizes a pointer of address 0, for which the address of the >> element reference yeilds the offset of the element. > >typedef struct { int f1; int f2; } Str; > >I tried OFFSET(Str,f2) on my machine and got 262,144 (=01000000 =2^18). >That's a pretty big offset considering it only has to pass >over one int. >I won't mention what Lint had to say about it. It could be because you used OFFSET(Str,f2) instead of the correct OFFSET(f2,Str). You got the parameters reversed. A simpiler definition of the OFFSET macro is the following: #define OFFSET(mos) ((long)(&(((char *)0)->mos))) This will produce a proper offset on almost all machines. (But not all, some machines have different formats to pointers to different types. Also, this macro assumes that (long)((char *)0) == 0L.) -- Disclaimer: | David Messer I'm always right and I never lie. | Software Consultant My company knows this and agrees | UUCP: ihnp4!quest!viper!dave with everything I say. | ihnp4!meccts!viper!dave