Linux核心中雙向鏈表的經典實現

來源:互聯網
上載者:User

概要

前面一章"介紹雙向鏈表並給出了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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.