Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

C/C++ Structure offset

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
", (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.

question from:https://stackoverflow.com/questions/142016/c-c-structure-offset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...