How to get a byte offset

Paul John Falstad pfalstad at phoenix.Princeton.EDU
Tue May 29 16:11:28 AEST 1990


In article <16802 at phoenix.Princeton.EDU> I write:
>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 ?
>The first way is just to add up all the sizeof values of a, b, and c.

Oops #1:  This doesn't work, since there might be padding.  (It was
a stupid suggestion anyway, and unnecessary, as it turns out.)

Oops #2:

>  d_offset = (char *) &foo->d - (char *) foo;
>Of course, the result isn't a constant, and code is generated.  You

Well, I'm not sure about the above example, but even Manx got this right:

#define d_offset ((int) &(((struct foo *) 0)->d))

The result IS an integer constant.  You can even use it for an array size,
although it may not be portable because of the NULL pointer.

-- 
Paul Falstad  PLINK:Hypnos GEnie:P.FALSTAD net:pfalstad at phoenix.princeton.edu
Disclaimer: My opinions, which belong to me and which I own, are mine.
-Anne Elk (not AN elk!)  The sun never set on the British empire because
the British empire was in the East and the sun sets in the West.



More information about the Comp.lang.c mailing list