How to get a byte offset

Jim Harkins jharkins at sagpd1.UUCP
Sat Jun 2 09:22:46 AEST 1990


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 ?

This is one of my minor pet peeves.  Why don't you just use the field name?
No matter how you count the offset, if anybody in the future changes the
structure then your code just broke.  The only valid reason that I can think
of for using an offset is that your passing the data structure to a routine
written in another language.  Even then, most languages (including modern
assemblers) provide methods of declaring structures and a little bit of fiddling
around takes care of things like padding.

>The reason I don't want to count the offset manually is, the size of the 
>"int"-type is machine dependent (may be 2 bytes or 4 bytes).

Thats exactly my point.  Being something of a snot, if I ever find someone
on my project counting byte offsets instead of using field names then I go
in and change the structure, ensureing I do so in such a way that all their
stuff breaks.  Then when they bitch at me about working weekends to fix
previously working code I can smile and walk away.  I repeat as needed, and
I've never had a problem with a boss in doing this.

Against my own good judgement, a good way to get the offset is to:

	char *head, *body;
	int offset;

	head = (char *) &structure;
	body = (char *) &structure.field_name;
	offset = body - head;

But please don't use this in your code.


-- 
jim		jharkins at sagpd1

I hate to see you go, but I love to see you walk away.



More information about the Comp.lang.c mailing list