C/C++ 结构偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/142016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:10:31  来源:igfitidea点击:

C/C++ Structure offset

c++coop

提问by davenpcj

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

IE:给定

struct mstct {
    int myfield;
    int myfield2;
};

I could write:

我可以写:

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

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

并获取offset 4输出。如果没有那个mstct thing声明/分配一个,我怎么能做到这一点?

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.

我知道&<struct>并不总是指向结构的第一个字段的第一个字节,我可以稍后解释。

回答by Michael Burr

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

标准的 offsetof() 宏(在 stddef.h 中)怎么样?

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

编辑:对于由于某种原因可能没有 offsetof() 宏可用的人,您可以使用以下内容获得效果:

#define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field))

回答by Dan Lenski

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

是的,使用offsetof宏,它(至少对于 GNU CC)可用于 C 和 C++ 代码:

offsetof(struct mstct, myfield2)

回答by Frank Krueger

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

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