This question already has answers here:
Does the 'offsetof' macro from <stddef.h> invoke undefined behaviour?
(6个答案)
2年前关闭。
这段代码怎么样,是标准代码吗?我已经在Visual C ++头文件中看到了这种代码,它可以计算某些结构成员的偏移量,但是它究竟如何工作?
编辑:
只是想起我以前在哪里看到此代码。在
(6个答案)
2年前关闭。
这段代码怎么样,是标准代码吗?我已经在Visual C ++头文件中看到了这种代码,它可以计算某些结构成员的偏移量,但是它究竟如何工作?
#include <iostream>
struct Foo
{
int a;
int b;
int c;
};
int main(int argc, char** argv)
{
int* i1 = (&((Foo*)0)->a);
int* i2 = (&((Foo*)0)->b);
int* i3 = (&((Foo*)0)->c);
std::cout << "i1 = " << i1 << "\ni2 = " << i2 << "\ni3 = " << i3 << "\n";
return 0;
}
Results : i1 = 0, i2 = 4, i3 = 8
编辑:
只是想起我以前在哪里看到此代码。在
WinNT.h
中#define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR)&(((type *)0)->field))
最佳答案
作为宏offsetof,这很常见。看看http://en.cppreference.com/w/cpp/types/offsetof。
它用作每个成员的内存位置和结构的内存位置的距离。在您的示例中,您将结构的存储位置设置为0,因此无需计算距离。
关于c++ - 计算结构成员的偏移量而无需实例化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41420250/