offsetof() operator. A tricky question.

Michael Meissner meissner at osf.org
Tue Mar 20 10:59:42 AEST 1990


In article <28008 at cup.portal.com> ts at cup.portal.com (Tim W Smith)
writes:

| < The answer could be simple and I used several times, do this:
| < 
| < struct astruct *ap;
| < 
| < ap = NULL;
| < 
| < offsetof_member0 = &ap->member0; /* zero offset */
| < offsetof_member1 = &ap->member1; /* sizeof(member0) */
| < 
| < An offsetof() operator would be quite handy here. But until then you can
| < use this with a good portability of your programs.
| 
| It IS simple.  It is also wrong.
| 
| If you want to have at least a small chance of working across different
| machines, try this:
| 
| 	offsetof_member0 = (ulong)&ap->member0 - (ulong)ap;
| 	...
| 						Tim Smith

Hmmm, in order to have a better chance of working, try:

	offsetof_member0 = ((char *)&ap->member0) - ((char *)ap);

This will work on machines which have weird pointer formats (such as
the Data General MV, the PR1ME 50 series, and the 80*86 in HUGE mode),
and will also work on machines which have pointers larger than the
largest integer type.

--
Michael Meissner	email: meissner at osf.org		phone: 617-621-8861
Open Software Foundation, 11 Cambridge Center, Cambridge, MA

Catproof is an oxymoron, Childproof is nearly so



More information about the Comp.lang.c mailing list