As far as i know "offsetof" macro is defined as :
#define offsetof(st, m) ((size_t)(&((st *)0)->m))
based on this link : http://en.wikipedia.org/wiki/Offsetof
So I write my own code snippet to calculate offset of a struct members:
typedef struct{
char a;
int b;
int c;
}example_struct;
int main(int argc, char *argv[])
{
example_struct *p = 0;
printf("%p\n", &(p->a)); --> 00000000
printf("%p\n", &(p->b)); --> 00000004
printf("%p\n", &(p->c)); --> 00000008
printf("%p\n", &(p->a)); --> 0
printf("%p\n", &(p->b)); --> 4
printf("%p\n", &(p->c)); --> 8
cout << &(p->a); --> this line cause crash ???
cout << &(p->b); --> 00000004
cout << &(p->c); --> 00000008
cout << (unsigned int)&(p->a); --> 0
cout << (unsigned int)&(p->b); --> 4
cout << (unsigned int)&(p->c); --> 8
return 0;
}
My questions are:
- Does the type-cast cause the crash. Why can`t cout the offset of the first member but printf can?
- Why should we type-cast. Is that must be done ?
Any opinions are truely appreciated :)