[英]How to compute offset between two different struct members in C?
Consider the following C code: 考虑以下C代码:
struct Foo
{
short a;
long b;
char c;
void* d;
};
I know it is possible to know the size of the entire structure using sizeof. 我知道可以使用sizeof知道整个结构的大小。 Is it possible to know the size of a subset of this structure, or (stated differently) know the distance between two members?
是否可能知道此结构子集的大小,或者(以不同的方式陈述)知道两个成员之间的距离? I realize could nest structures based on the offsets I want (then it is possible to use sizeof), but say I wanted to know the number of bytes between a and d?
我意识到可以基于我想要的偏移量嵌套结构(然后可以使用sizeof),但是我想知道a和d之间的字节数吗? Also, I'd like to do this without instantiating an object (something like sizeof).
另外,我想在不实例化对象的情况下执行此操作(类似于sizeof)。 (I realize if I have a object, then I could look at the address differences between foo.d and foo.a).
(我意识到如果我有一个对象,那么我可以看看foo.d和foo.a之间的地址差异)。 Is this possible?
这可能吗?
offsetof(Foo, d) - offsetof(Foo, a)
offsetof
gives you the offset from the beginning of Foo
to the member specified. offsetof
为您提供从Foo
开头到指定成员的偏移量。
You'll need #include <stddef.h>
您需要
#include <stddef.h>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.