2011-12-22 51 views
4

這是宏定義:的(字符*)投在Linux內核的LIST_ENTRY()鏈表實現

/** 
* 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))) 

我不明白爲什麼PTR澆鑄到(char *)。我不能只從ptr減去member的偏移量嗎?像這樣:

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

謝謝!

回答

5

號指針運算等同於:

ptr[addend] 

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

後者需要顯式轉換到char *(因爲這是存儲器的單元)直接操作的指針的值。

+0

我想你的意思是'(unsigned long)&ptr'。 – 2011-12-22 19:18:30

+0

@DanielFischer,的確如此。修正了,謝謝! – MSN 2011-12-22 19:41:40