Skip to contentSkip to conversation

Question with "container_of(ptr, type, member)"

DISCUSSION peter 2 participants 3 messages Aug 30, 2011 – Aug 31, 2011

lore
Share & tools
lore

peter

author
#0 lore raw

I have a question about the macro " container_of(ptr, type, member) " I can write it as this,

 #define container_of(ptr, type, member) ({ \
	(type *) ((char *) ptr - offset_of(type, member)); \
	})
It can act the same as 
#define container_of(ptr, type, member) ({            \
	 const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
	 (type *)( (char *)__mptr - offsetof(type,member) );})

So why we don't use the first one ?
Thanks for your answer.
(I am a kernel newbie ,and sorry for my poor english~)

#1 lore raw
Quoted 9 lines · peter

I have a question about the macro " container_of(ptr, type, member) " I can write it as this,

  #define container_of(ptr, type, member) ({ \
	(type *) ((char *) ptr - offset_of(type, member)); \
	})
It can act the same as
#define container_of(ptr, type, member) ({            \
	 const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
	 (type *)( (char *)__mptr - offsetof(type,member) );})
Quoted 3 lines

So why we don't use the first one ?
Thanks for your answer.
(I am a kernel newbie ,and sorry for my poor english~)

The version used by the Linux kernel does type checking.

~Ryan

author
#2 lore raw

I see now, It can gives an waring: "warning: initialization from incompatible pointer type", when give it an wrong type. thanks for your answer!

Quoted 18 lines · Ryan Mallon
Quoted 9 lines · peter

I have a question about the macro " container_of(ptr, type, member) " I can write it as this,

  #define container_of(ptr, type, member) ({ \
	(type *) ((char *) ptr - offset_of(type, member)); \
	})
It can act the same as
#define container_of(ptr, type, member) ({            \
	 const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
	 (type *)( (char *)__mptr - offsetof(type,member) );})
Quoted 3 lines

So why we don't use the first one ?
Thanks for your answer.
(I am a kernel newbie ,and sorry for my poor english~)

The version used by the Linux kernel does type checking.

~Ryan