How to get a byte offset

Karl Heuer karl at haddock.ima.isc.com
Tue Jun 5 09:10:14 AEST 1990


In article <1990May28.131914.11205 at virtech.uucp> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
>In article <1990May28.034643.6962 at cs.umn.edu> swie at 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 <stddef.h>.
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 at ima.ima.isc.com or harvard!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list