tags:

views:

2803

answers:

3

I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.

IE: given

struct mstct {
    int myfield;
    int myfield2;
};

I could write:

mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));

And get "offset 4" for the output. How can I do it without that "mstct thing" declaration/allocating one?

I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later.

+19  A: 

How about the standard offsetof() macro (in stddef.h)?

Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:

#define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field))
Michael Burr
davenpcj
Wow - no stddef.h? Just out of curiosity, could I ask what you're using?
Michael Burr
It's in the C99 standard, so I'd suggest getting a new compiler.
wnoise
more than that - it's been in C since ANSI C89. I have no idea how common (or uncommon) it was pre-standard.
Michael Burr
I once had a C compiler that had offsetof() defined in stddef.h with the zero trick, but it also didn't allow the use of zero as a base address. (Long time ago - 1989, or thereabouts.) Workaround was to change 0 to 1024 instead.
Jonathan Leffler
+1  A: 

Right, use the offsetof macro, which (at least with GNU CC) is available to both C and C++ code:

offsetof(struct mstct, myfield2)
Dan
Michael Burr
Agreed - I'd most likely provide a dummy <stddef.h> to provide that macros. Plauger provides "The Standard C Library" and it is an easy header to provide - as long as it does not have to be portable.
Jonathan Leffler
Dan
+3  A: 

printf("offset: %d\n", &((mstct*)0)->myfield2);

Frank Krueger