Offsetof在Linux中使用 [英] Offsetof used in Linux
问题描述
我正在经历一个特定变量的偏差如何在给定结构中发现。
I was going through how offset of a particular variable is found in a given structure.
我尝试下面的程序。
struct info{
char a;
int b;
char c;
int d;
};
struct info myinfo;
int main(int argc, char **argv)
{
struct info *ptr = &myinfo;
unsigned int offset;
offset = (unsigned int) &((struct info *) 0)->d;
printf("Offset = %d\n",offset);
return 0;
}
我只是想知道如何偏移量=(无符号整数)行及((结构信息*)0) - D 1和D
的作品。
我因为0提领的困惑
I just wanted to know how the line offset = (unsigned int) &((struct info *) 0)->d
works.
I am confused because of dereferencing of 0.
推荐答案
它没有的真正的间接引用 0
,虽然它看起来像它。这确实需要一些成员的地址,如果在地址解引用 0
,假设
It does not really dereference 0
, although it looks like it. It really takes the address of some member if it was dereferenced at address 0
, hypothetically.
这是一种肮脏的黑客(另外,一些讨厌的东西宏),但它可以让你什么你感兴趣的(在结构中的偏移量成员)。
This is a kind of dirty hack (plus, some nasty macro stuff), but it gets you what you're interested in (the offset of the member in the struct).
做同样的事情会产生一个有效的对象,以它的地址,并采取成员的地址,然后减去这些的更正确的方式。做同样的一个空指针是不是所有的pretty,但没有创建一个对象,并减去任何工作。
A more "correct" way of doing the same thing would be to generate a valid object, take its address, and take the address of the member, then subtract these. Doing the same with a null pointer is not all pretty, but works without creating an object and subtracting anything.
这篇关于Offsetof在Linux中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!