structure element offsets

Miles Bader bader at spice.cs.cmu.edu
Mon Nov 24 17:53:05 AEST 1986


Is there any way of finding the offset of a structure element from
the beginning of a structure in a portable AND efficient way?  I have
a structure that looks like this:

struct fentry{
    FPOOL   *pool;
    union{
	FENTRY	*next;
	char    buf[1]; /* extended as needed ... */
    }	    data;
};

And I want to find the base of the structure given address of buf.
My first one went like:

static fentry calc;
#define FALLOC_OFFSET    ((long)calc.data.buf-(long)&calc)

This worked, and with pcc on an sun, compiled into the correct
constant, 4.  However on an ibm rt (under both pcc and another
non-pcc compiler), it did the calculation at run time (despite the
fact that the two quantities being subtracted were the same address
with offsets differing by 4).

I have given up and defined this as the constant 4 (which it is on
any machine around here), but am just curious if there's a better
way.

				    -Miles



More information about the Comp.lang.c mailing list