C / C ++结构失调 [英] C/C++ Structure offset
问题描述
我找了一块code,可以告诉我一个字段的偏移结构中不分配结构的一个实例。
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浏览器:给定
struct mstct {
int myfield;
int myfield2;
};
我可以写:
mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
和得到弥补4的输出。我怎么能做到这一点不说,mstct事报关/分配呢?
And get "offset 4" for the output. How can I do it without that "mstct thing" declaration/allocating one?
我知道,和放大器;<&结构GT;并不总是在结构的第一场的第一个字节指出,我可以占到稍后
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.
推荐答案
如何offsetof()宏(在STDDEF.H)标准?
How about the standard offsetof() macro (in stddef.h)?
编辑:人谁可能没有提供某种原因offsetof()宏,您使用类似可以得到的效果:
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))
这篇关于C / C ++结构失调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!