Invictus
Invictus

Reputation: 2780

What is this macro exactly doing?

#define offsetof(type, member)  ((size_t)(&((type *)0)->member))

I am not understanding (&((type *)0)->member) what is this exactly telling me.....

here type may be a structure or something else??...

More specifically what is that 0 telling me here??

Upvotes: 5

Views: 206

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375982

This is to determine the offset of a struct field. It works by using 0 as the address of the struct, then asking for the address of the field:

(type *)0

is 0 as a pointer to type

&((type *)0)->member

is the address of that hypothetical struct's member member. If the address of the struct is 0, then the address of the member is the same as the offset from the beginning of the struct.

((size_t)(&((type *)0)->member))

is that address cast to a size_t to be the proper type for an offset.

Upvotes: 6

mattjgalloway
mattjgalloway

Reputation: 34912

I break it down like this:

  1. (type *)0 - casting 0 to a pointer to type "type". i.e. imagine for a minute that there's an object of type "type" at memory address 0.

  2. ->member - look into the object for the field called member.

  3. & - take the address of that.

You could also write it like this:

((size_t)((&((type *)x)->member) - x))

But we're cheating and using 0 so that there's no offset to take off at the end.

Upvotes: 2

Jamie
Jamie

Reputation: 7441

The macro is casting an address (0) to a declared type ("type") then accessing a field ("member") and getting the address. The result is that the address of the field, offset from address 0, gives the offset form the beginning of the type (structure/union) to the field.

Upvotes: 3

Related Questions