finding offset of a member in C structures

Doug Gwyn gwyn at smoke.brl.mil
Mon May 20 14:09:18 AEST 1991


In article <1276 at unisql.UUCP> pckim at unisql.UUCP (Pyung-Chul Kim) writes:
-	struct a_struct {
-		short	member1;
-		char	member2;
-		int	memner3;
-	};
-can I get the offset of member2 at *compiling time* and *portably* ?

Yes, but you shouldn't very often need to do so.

-It is possible to provide a compiler operator:
-	offsetof(member_name,structure_type_name)
-as it provides 'sizeof' operator.
-Do you know if there is a compiler operator like above, or is there any
-alternative solution.

Standard C provides an offsetof() macro, but you don't really need one.
	struct a_struct foo;
	int offset2 = (char *)&foo.member2 - (char *)&foo; /* for example */



More information about the Comp.lang.c mailing list