概要
前面一章"介紹雙向鏈表並給出了C/C++/Java三種實現",本章繼續對雙向鏈表進行探討,介紹的內容是Linux核心中雙向鏈表的經典實現和用法。其中,也會涉及到Linux核心中非常常用的兩個經典宏定義offsetof和container_of。內容包括:
1. Linux中的兩個經典宏定義
2. Linux中雙向鏈表的經典實現
轉載請註明出處:http://www.cnblogs.com/skywang12345/p/3562146.html
更多內容: 資料結構與演算法系列 目錄
Linux中的兩個經典宏定義
倘若你查看過Linux Kernel的源碼,那麼你對 offsetof 和 container_of 這兩個宏應該不陌生。這兩個宏最初是極客寫出的,後來在Linux核心中被推廣使用。
1. offsetof
1.1 offsetof介紹
定義:offsetof在linux核心的include/linux/stddef.h中定義。
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
說明:獲得結構體(TYPE)的變數成員(MEMBER)在此結構體中的位移量。
(01) ( (TYPE *)0 ) 將零轉型為TYPE類型指標,即TYPE類型的指標的地址是0。
(02) ((TYPE *)0)->MEMBER 訪問結構中的資料成員。
(03) &( ( (TYPE *)0 )->MEMBER ) 取出資料成員的地址。由於TYPE的地址是0,這裡擷取到的地址就是相對MEMBER在TYPE中的位移。
(04) (size_t)(&(((TYPE*)0)->MEMBER)) 結果轉換類型。對於32位系統而言,size_t是unsigned int類型;對於64位系統而言,size_t是unsigned long類型。
1.2 offsetof樣本
代碼(offset_test.c)
1 #include <stdio.h> 2 3 // 獲得結構體(TYPE)的變數成員(MEMBER)在此結構體中的位移量。 4 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 5 6 struct student 7 { 8 char gender; 9 int id;10 int age;11 char name[20];12 };13 14 void main()15 {16 int gender_offset, id_offset, age_offset, name_offset;17 18 gender_offset = offsetof(struct student, gender);19 id_offset = offsetof(struct student, id);20 age_offset = offsetof(struct student, age);21 name_offset = offsetof(struct student, name);22 23 printf("gender_offset = %d\n", gender_offset);24 printf("id_offset = %d\n", id_offset);25 printf("age_offset = %d\n", age_offset);26 printf("name_offset = %d\n", name_offset);27 }