0

What about this code, is it standard ? I've seen that kind of code in a Visual C++ header, it can calculate the offsets of some structure members but how does it works exactly ?

#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

Edit : Just remembered where I saw this code before. It's in WinNT.h

#define FIELD_OFFSET(type, field)    ((LONG)(LONG_PTR)&(((type *)0)->field))
nikau6
  • 922
  • 9
  • 16

1 Answers1

2

That is pretty common, as macro offsetof. Take a look at http://en.cppreference.com/w/cpp/types/offsetof.

It works as the distance of each member's memory location and struct's memory location. In case of your example, you set struct's memory location as 0, thus no need to calculate distance.

xosp7tom
  • 2,131
  • 1
  • 17
  • 26
  • If you set your memory location as 0 ... wouldn't the operator "->" be segmentation fault? – ChaoSXDemon Jan 02 '17 at 00:39
  • 3
    segfault happens when you are actually trying to access the member variable or call the member function. With &, you are just calculating memory address. – xosp7tom Jan 02 '17 at 00:40
  • 1
    Even starting at location 0 it can still be useful to calculate the offsets. – nikau6 Jan 02 '17 at 00:48