4/6 In C, how do I get the offset of a field in a struct? E.g.
typedef struct {
char MS_foo;
int MS_bar;
} MyStruct;
I want to use the offset of MS_bar (which is 1) in compile-time.
\_ It most likely isn't 1 on any modern architecture.
The compiler will pad it so the int starts on a 32-bit
boundary on almost all 32-bit machines.
\_ ((MyStruct*)0)->MS_bar
\_ don't you mean (int)(&((MyStruct*)0)->MS_bar) ? -ali
\_ This works. Thanks!
\_ MyStruct crap;
bar_offset = &(crap.MS_bar) - &crap;
\_ You don't wanna go there. This is machine specific stuff. If you
want to write portable code, there are lots of other ways to do
what you want.
\_ no, the ways outlined above are not machine dependent. what
are you talking about? maybe there's some fine print in the
standard that says the above won't work, but really, it works
doing this is using C++ and using member objects.
and you shouldn't be pedantic about it. another good way of
doing this is using C++ and using member objects. -ali
\_ Dude. You don't know what you are talking about. The
way in which variable sized members of a struct are
positioned within the struct are, and should be,
implementation specific according to the standard. Shut
up and go away. You know nothing. Don't give advice here.
You are a fool. Sign your name.
\_ ok, you go and underline for me in the above specified
code the machine specific stuff that is susceptible to
padding differences and data type size and reordering.
\_ Sure. The above data structure has a character
(generally 8 bits), followed by an int (generally
16 or 32 bits). Depending on how the memory on the
target computer is arranged, the offset of the second
member (the integer) could be 8, 16, 32, or maybe even
some wierd non-power-of-2 number. You have said this
yourself, the implementation is free to pad (I am not
sure it is allowed to reorder though).
ok? -ali. And sign your name yourself.
\_ Example?
\_ What are you trying to do, exactly?
\_ I want to print out all the fields in a variable of
a certain big struct, so I think I should make a table
of field informations, like this:
typedef struct {
char *FE_string;
int FE_offset;
int FE_type;
} FieldEntry;
FieldEntry fieldTable[] = {
{"MS_foo", <offset of MS_foo>, TYPE_CHAR},
{"MS_bar", <offset of MS_bar>, TYPE_INT},
......
};
Then I use printf() to print the fields according to the
types.
\_ Why do you need field offsets in the first place?
\_ Then I can just traverse the table to print
out all the fields passing the appropriate format
strings to printf() according to the field type,
rather than writing 100 printf()'s for 100 fields.
\_ Use a macro, then cut and paste from the struct
definition.
\_ But I think using a table reduces code size
a bit. |