r/linuxdev • • Oct 27 '17

Container_of and offset_of understanding

Could someone explain to me these two macros?

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define container_of(ptr, type, member) ({            \
 const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
 (type *)( (char *)__mptr - offsetof(type,member) );})

I understand everything except why offset_of is of (size_t) and container_of has (char *)?

How would (char *) -(size_t) work in this macro?

I would have expected both of them to be of the same type. like char * for example.

4 Upvotes

4 comments sorted by

View all comments

Show parent comment

2

u/imMute Oct 27 '17

Because offsetof is returning the offset as a byte count, which is typically a size_t. Its a count, not a pointer that you can dereference.

As for the pointer math, consider this code:

char *str = ...
putc(str + 2);
putc(str - 2);

In that the "2" is an int, and definitely not a pointer.

1

u/sbay Oct 27 '17

Wow! Excellent example.

Thank you! I got it.