What exactly does this macro do?

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

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

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

More specifically, what is it, telling me here?

+5
source share
3 answers

I will break it like this:

  • (type *)0- cast 0to type pointer " type". those. imagine for a minute that there is an object of type " type" at memory address 0.

  • ->member- look at the object for the field called member.

  • & - take the address of this.

You can also write it like this:

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

But we cheat and use 0so that there is no bias at the end.

+2
source

. , 0 , :

(type *)0

0 type

&((type *)0)->member

- member. 0, .

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

- , , size_t, .

+6

The macro gives the address (0) to the declared type ("type"), then refers to the field ("member") and receives the address. The result is that the field address offset from address 0 gives an offset forming the beginning of the type (structure / union) in the field.

+3
source

All Articles