Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!snorkelwacker!spdcc!ima!haddock!karl From: karl@haddock.ima.isc.com (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: How to get a byte offset Message-ID: <16787@haddock.ima.isc.com> Date: 4 Jun 90 23:10:14 GMT References: <1990May28.034643.6962@cs.umn.edu> <1990May28.131914.11205@virtech.uucp> Reply-To: karl@haddock.ima.isc.com (Karl Heuer) Distribution: usa Organization: Interactive Systems, Cambridge, MA 02138-5302 Lines: 25 In article <1990May28.131914.11205@virtech.uucp> cpcahil@virtech.UUCP (Conor P. Cahill) writes: >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 ? In ANSI C, you use the macro offsetof(), which you import from . If you don't have it, you have to roll your own. There is no portable definition which is guaranteed to evaluate to a compile-time constant, but for any particular machine it's likely that one or more of the versions posted here will happen to work. >Here are a few examples: >#define offsetof(elem,str) (&(((struct str *)0)->elem)) The args are in the wrong order, and the one named `str' has to be a struct tag rather than a type. (If you have to reinvent the wheel, you might as well make it consistent with everybody else's wheel, especially if you use the same name.) Also, the result is a pointer; it ought to be an integer. Some better choices are: #define offsetof(T,mem) ((size_t)(char *)&((T *)0)->mem) #define offsetof(T,mem) ((char *)&((T *)0)->mem - (char *)0) #define offsetof(T,mem) ((char *)&((T *)&X)->mem - (char *)&X) In the third one, X is any convenient object. Karl W. Z. Heuer (karl@ima.ima.isc.com or harvard!ima!karl), The Walking Lint