How to get a byte offset

Conor P. Cahill cpcahil at virtech.uucp
Mon May 28 23:19:14 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 ?

Here are a few examples:

/*
 * the first one works using the structure type name and does not
 * require the runtime existance of any occurance of such a structure.
 * NOTE: this may be non-portable due to the use of a NULL pointer.
 */
#define	offsetof(elem,str)	(&(((struct str *)0)->elem))

/*
 * the following one requires an occurance of the structure itself and 
 * should be relatively portable.
 */

#define myoffset(elem,data)	( ((char *) &data.d) - ((char *)&data) )

struct my_struct_type {
int	a;
char	b[3];
int	c[10];
char	d;
} my_name;


main()
{

	printf( "offsetof(d,my_struct_type) = %d\n",offsetof(d,my_struct_type));
	printf( "myoffset(d,my_name) = %d\n",myoffset(d,my_name));
}

-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.lang.c mailing list