handy.h: macro

tom thumbs tp at wucs.UUCP
Wed Sep 11 12:39:41 AEST 1985


    The macro OFFSETV is good for finding the offset of a
certain variable within a structure. OFFSET can also be used,
if one is careful to hand it an address. [ hopefully, the
example below will explain what this is doing.]
    (As noted below, these should be used carefully.)
    Anyway, I found these exceedingly useful when doing lots of
database stuff with intricate structures.
    I believe that credit for coming up with these belongs to
Brian Thomas of AT&T (ihnp4!we53!bmt).
---------------------handy macro & example below ----------
#include <stdio.h>

/* the two lines below contain the wild macros -- cautious people
    will put parens are the X and Y on right-hand side */
#define OFFSET(X, Y)	( (int) ((struct X *)0)-> Y )
#define OFFSETV(X, Y)	( (int) &((struct X *)0)-> Y )

struct foo {		/* simple example structure type	*/
    int harris;
    char torek[6];
    long gwyn;
} ;

main()
{
    printf(" offset harris=%d, gwyn=%d, torek=%d, alt. torek=%d\n",
	OFFSETV(foo, harris), 
	OFFSETV(foo, gwyn), 
	OFFSETV(foo, torek[0]),
	OFFSET(foo, torek) );
}

-----------------------------------------------------------------

   On VAX 750 with 4.2 BSD (version Kurt) we get output of:

 offset harris=0, gwyn=12, torek=4, alt. torek=4

    (note gwyn is word-aligned, of course)
--------
WARNINGS: may cause weird alignment problems!! Also, you better
    know the difference between arrays and pointers (in other words,
    this is dangerous for novices, and probably others as well).
--
   ...tp...
       tom patterson
	   ... {seismo, ihnp4}!wucs!tp



More information about the Comp.lang.c mailing list