0

Recently I saw this macro:

#define asOFFSET(s,m) ((size_t)(&reinterpret_cast<s*>(100000)->m)-100000)

I have found this as the approach to calculate the position offset of any item m of any struct s from the beginning of the structure.

However when I ran it and compared the calculation for two structures MyStuct2 and MyStruct3, which differ only by one int var3 added to MyStruct3 at the beginning, I got the difference 8 bytes, not 4 as I expected.

This is the code I run:

#include <time.h>
#include <stdio.h>

#define asOFFSET(s,m) ((size_t)(&reinterpret_cast<s*>(100000)->m)-100000)


struct MyStruct1 {int var1; int a;};
struct MyStruct2 {long var2; int a;};
struct MyStruct3 {int var3; long var4; int a;};

int main (void)
{

 printf("%d\n",(int)asOFFSET(MyStruct1,a));
 printf("%d\n",(int)asOFFSET(MyStruct2,a));
 printf("%d\n",(int)asOFFSET(MyStruct3,a));

 // Result:
 // 4
 // 8
 // 16

}

and this is the output it gives:

4
8
16

My question is how can I fix the real memory in order to have one int taking 4 bytes and not 8? Thanks.

Ruslan Gerasimov
  • 1,752
  • 1
  • 13
  • 20

0 Answers0