1
int main()
{
    typedef struct name
    {
        long a;
        int b;
        long c;
    } r;
    r re = { 3, 7, 5 };

    printf("%d", ((unsigned int)&(( struct name *)0)->b));

    printf("%d", ((int)&((struct name *)0)->a));

    while(1);
}

I find that the program gives the offset of the member of the structure. So, probably similar to offsetof(). But, This is the first time i am seeing the typecast with '0'. What does that mean ?

Chnossos
  • 9,971
  • 4
  • 28
  • 40
  • possible duplicate of [Is apparent NULL pointer dereference in C actually pointer arithmetic?](http://stackoverflow.com/questions/4532797/is-apparent-null-pointer-dereference-in-c-actually-pointer-arithmetic) – M.M Nov 13 '14 at 10:05

1 Answers1

3

Yes, this is an attempt to implement offsetof. They're putting the beginning of the struct pointer at 0, such that the addres of b will indicate its offset.

However, this is not good code. First, dereferencing a null pointer (as is done with ->b) is undefined behavior, even if nothing is done with that value other than taking a pointer to it. Secondly (and this is where it gets weird), the null pointer -- despite being written 0 -- is not guaranteed to actually be at location 0 in memory, so the result casted to an int is not necessarily the offset of the member.

Some standard library implementations do implement offsetof this way, if they are meant to work with compilers which are willing to deal with those standard-violating problems. However, you should not rely on this in your own code. That's what offsetof is for.

Sneftel
  • 40,271
  • 12
  • 71
  • 104