Something new for C?

Gordon Cross crossgl at ingr.UUCP
Wed Nov 9 02:56:06 AEST 1988


In article <73 at dsoft.UUCP>, root at dsoft.UUCP (Super user) writes:
> Maybe I've missed something in C, but One of the things I've never found a
> way to do and have always wanted, was a precompiler command to allow me to
> use the offset of an item into a structure. for example:
> 
> struct test {
>    long this;
>    int  that;
>    char those[8];
> };
> 
>    val = offset(test,that);

Sure.  Try this:

#define  offset(type,field) ((unsigned int)&((type *)0)->field)

where "type" is the type of your struct (or union) and "field" is the name of
the field you want the offset for.  Any decent compiler should be able to
evaluate this at compile time.  For your example, you would use:

     val = offset (struct test, that);

NOTE:  if "unsigned int" is only 16 bits long on your implementation, you may
       want to use "unsigned long" to handle large structs like

       struct big {
         char buffer[70000];
         int  tail;
       };

       val = offset (struct big, tail);


Gordon Cross
Intergraph Corp.  Huntsville, AL



More information about the Comp.lang.c mailing list