C/C++ Structure offset

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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 & does not always point at the first byte of the first field of the structure, I can account for that later.

回答1:

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


回答2:

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

offsetof(struct mstct, myfield2)


回答3:

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



转载请标明出处:C/C++ Structure offset
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!