0

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 :)

4

1 回答 1

0

据我所知,“offsetof”宏定义为......

它不是这样定义的。可以这样定义。通常,对指针执行指针运算NULL会导致未定义的行为,但如果您的 C 库恰好这样做,那么它在您的特定系统上一定没问题。

顺便说一句,这对我来说在 OS X 10.9 上也崩溃了clang++。但是,它不会崩溃offsetof。结论:未定义的行为是未定义的,实现细节就是实现细节,你不应该依赖它们或对它们做出假设。

于 2014-04-18T09:47:47.643 回答