(char *) in the list_entry () list of the Linux kernel linked list implementation

This is the macro definition:

/** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) 

I do not understand why ptr is thrown on (char *) . Can't I just subtract member offset from ptr ? Like this:

 #define list_entry(ptr, type, member) \ ((type *)((ptr)-(unsigned long)(&((type *)0)->member))) 

Thanks!

+4
source share
1 answer

No. Pointer arithmetic is equivalent to:

 ptr[addend] 

not

 (ptr_type *)((unsigned long)&ptr + addend) 

The latter requires explicit casting to char * (since this is a unit of memory) to directly control the value of the pointer.

+5
source

Source: https://habr.com/ru/post/1387622/


All Articles