117.info
人生若只如初见

用container_of宏解决链表问题

container_of 宏是一个用于在 Linux 内核中获取容器结构体指针的实用宏

以下是一个简单的示例,说明如何使用 container_of 宏解决链表问题:

#include
#include 

// 定义一个链表节点结构体
typedef struct list_node {
    int data;
    struct list_node *next;
} ListNode;

// 定义一个包含链表节点的容器结构体
typedef struct container {
    int id;
    ListNode node;
} Container;

// 创建一个新的容器并初始化其链表节点
Container *create_container(int id, int data) {
    Container *container = (Container *)malloc(sizeof(Container));
    container->id = id;
    container->node.data = https://www.yisu.com/ask/data;>node.next = NULL;
    return container;
}

// 使用 container_of 宏获取容器结构体指针
Container *get_container_from_node(ListNode *node) {
    return container_of(node, Container, node);
}

int main() {
    // 创建两个容器并初始化其链表节点
    Container *container1 = create_container(1, 10);
    Container *container2 = create_container(2, 20);

    // 将两个容器的链表节点连接起来
    container1->node.next = &container2->node;

    // 通过链表节点获取容器结构体指针
    Container *found_container = get_container_from_node(container1->node.next);

    // 输出找到的容器的 ID 和数据
    printf("Found container with ID: %d and data: %d\n", found_container->id, found_container->node.data);

    // 释放分配的内存
    free(container1);
    free(container2);

    return 0;
}

在这个示例中,我们定义了一个链表节点结构体 ListNode 和一个包含链表节点的容器结构体 Container。我们创建了两个容器并将它们的链表节点连接起来。然后,我们使用 container_of 宏从链表节点获取容器结构体指针,并输出找到的容器的 ID 和数据。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe584AzsBAQJSDA.html

推荐文章

  • container_of的使用方法是什么

    container_of 是一个 C 语言宏,用于通过结构体成员的指针获取包含该成员的结构体的指针。
    它的使用方法如下:
    #define container_of(ptr, type, memb...

  • 在C语言中如何安全使用container_of

    在C语言中,container_of宏通常用于获取包含特定成员的结构体的指针。使用container_of宏时,需要确保传入的参数是有效的,并且结构体的成员的偏移量是正确的,以...

  • container_of宏与offsetof宏的关系

    container_of宏和offsetof宏是在C语言中用来处理结构体的宏。
    offsetof宏用于获取结构体中特定成员变量的偏移量,其定义如下:
    #define offsetof(TYPE...

  • 为什么说container_of宏很有用

    container_of宏非常有用,因为它提供了一种在数据结构中获取包含该结构的容器结构的简单且有效的方法。通过container_of宏,可以从一个结构体成员的地址获取该结...

  • container_of宏在不同编译器下的兼容性

    container_of 宏是一个用于获取结构体实例指针的宏,通常用于 Linux 内核编程
    以下是一个简单的示例:
    #include
    #include struct container { in...

  • 如何用container_of宏实现类型转换

    container_of 是一个宏,用于在 Linux 内核和其他 C 语言项目中实现类型转换
    以下是 container_of 宏的定义:
    #define container_of(ptr, type, membe...

  • container_of宏在驱动程序开发中的意义

    container_of 是一个 C 语言宏,用于在驱动程序和内核编程中获取包含特定成员的结构体实例
    在驱动程序开发中,container_of 宏通常用于处理设备、文件或其他...

  • container_of宏与内存布局的关系

    container_of 宏是一个用于获取结构体实例的指针,通过其成员变量的指针
    在 C 语言中,结构体的内存布局是连续的。这意味着结构体中的成员变量在内存中是按...