Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!uunet!virtech!cpcahil From: cpcahil@virtech.uucp (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: How to get a byte offset Message-ID: <1990May28.131914.11205@virtech.uucp> Date: 28 May 90 13:19:14 GMT References: <1990May28.034643.6962@cs.umn.edu> Reply-To: cpcahil@virtech.UUCP (Conor P. Cahill) Distribution: usa Organization: Virtual Technologies Inc., Sterling VA Lines: 39 In article <1990May28.034643.6962@cs.umn.edu> swie@cs.umn.edu (S. T. Tan) writes: >Is there an easy way to get the byte offset of a field in a structure without >counting it manually ? Here are a few examples: /* * the first one works using the structure type name and does not * require the runtime existance of any occurance of such a structure. * NOTE: this may be non-portable due to the use of a NULL pointer. */ #define offsetof(elem,str) (&(((struct str *)0)->elem)) /* * the following one requires an occurance of the structure itself and * should be relatively portable. */ #define myoffset(elem,data) ( ((char *) &data.d) - ((char *)&data) ) struct my_struct_type { int a; char b[3]; int c[10]; char d; } my_name; main() { printf( "offsetof(d,my_struct_type) = %d\n",offsetof(d,my_struct_type)); printf( "myoffset(d,my_name) = %d\n",myoffset(d,my_name)); } -- Conor P. Cahill (703)430-9247 Virtual Technologies, Inc., uunet!virtech!cpcahil 46030 Manekin Plaza, Suite 160 Sterling, VA 22170