Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site wucs.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxt!houxm!ihnp4!wucs!tp From: tp@wucs.UUCP (tom thumbs) Newsgroups: net.lang.c Subject: handy.h: macro Message-ID: <1153@wucs.UUCP> Date: Tue, 10-Sep-85 22:39:41 EDT Article-I.D.: wucs.1153 Posted: Tue Sep 10 22:39:41 1985 Date-Received: Wed, 11-Sep-85 20:13:10 EDT Organization: Kurt's Krunchers (Wash U) Lines: 48 Keywords: offsets within structures 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 /* 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