溫馨提示×

c語言containerof函數(shù)怎么用

小億
108
2023-11-10 19:30:30
欄目: 編程語言

在C語言中,container_of函數(shù)用于獲取包含某個成員的結構體的指針。

container_of函數(shù)的原型如下:

#define container_of(ptr, type, member) ({ \
    const typeof(((type *)0)->member) *__mptr = (ptr); 
    (type *)((char *)__mptr - offsetof(type, member)); })

其中,參數(shù)ptr是成員的指針,type是結構體的類型,member是成員在結構體中的名稱。

使用container_of函數(shù)的步驟如下:

  1. 確保結構體中的成員具有已知的偏移量。
  2. 通過指向成員的指針ptr,調用container_of函數(shù),并傳入相關參數(shù)。
  3. container_of函數(shù)將返回指向包含成員的結構體的指針。

下面是一個使用container_of函數(shù)的示例:

#include <stddef.h>

struct Student {
    int id;
    char name[20];
};

int main() {
    struct Student s;
    int *ptr_id = &s.id;
    struct Student *ptr_student = container_of(ptr_id, struct Student, id);
    
    return 0;
}

這個示例中,我們定義了一個結構體Student,其中包含了一個成員id。在main函數(shù)中,我們取得成員id的指針ptr_id,然后調用container_of函數(shù),通過ptr_id獲取到包含成員id的結構體指針ptr_student。

需要注意的是,使用container_of函數(shù)時,需要確保成員的偏移量是已知的,否則可能會得到錯誤的結果??梢酝ㄟ^offsetof宏來獲取成員的偏移量。

0