Chinaunix首页 | 论坛 | 博客
  • 博客访问: 13144
  • 博文数量: 7
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 80
  • 用 户 组: 普通用户
  • 注册时间: 2020-04-07 23:18
文章存档

2020年(7)

我的朋友
最近访客

分类: LINUX

2020-05-15 21:58:49

 常规的思维,建一个链表,都是想在节点构建某个对象的属性,而linux的链表相反,是在对象内添加链表属性。但是这样带来问题就是想通过(结构元数)链表遍历每个节点很不方便,于是就有以下通过存储位置获取对象的宏:

点击(此处)折叠或打开

  1. struct list_head {
  2.     struct list_head *next, *prev;
  3. };

  4. /**
  5.  * list_entry - get the struct for this entry
  6.  * @ptr:    the &struct list_head pointer.
  7.  * @type:    the type of the struct this is embedded in.
  8.  * @member:    the name of the list_struct within the struct.
  9.  */
  10. #define list_entry(ptr, type, member) \
  11.     container_of(ptr, type, member)
  12. //这里通过menber成员获取type类型的结构对象的地址。ptr是member的实际的地址。
  13. #define offsetof(TYPE,MEMBER)   ((size_t) &((TYPE *)0)->MEMBER)
    /*通过该宏获取成员member在type中的偏移位置。(TYPE *)0 是把0地址转换为TYPE指针类型,然后从这个指针上“取”MEMBER成员再取址。
    是骗编译器说有一个指向类(或结构)TYPE的指针,其值为0  ,这时MEMBER的地址当然就是MEMBER在TYPE中的偏移了 .
      */
  14. #define LIST_HEAD_INIT(name) { &(name), &(name) }初始化链表的两个成员

  15. #define LIST_HEAD(name) \
  16.     struct list_head name = LIST_HEAD_INIT(name)

  17. static inline void INIT_LIST_HEAD(struct list_head *list)
  18. {
  19.     list->next = list;
  20.     list->prev = list;
  21. }
  22. 遍历链表例子:
  23. struct student
    {
    int grade;
    int unit;
    char* name;
    float shengao;
    struct student *next;
    };

    static struct student *file_systems;
    struct student** find_student_byname(char* name,unsigned len)
    {
    //p所指向的值也是一个指针,即p指向的值也是一个地址
    struct student** p;
    // for,中条件部分 (*p).当*p指向实际地址,满足条件、进循环。
    for(p = &file_systems;*p; p = &((*p)->next))
    {
         if( strncmp(name,(*p)->name,len) == 0 && len == strlen((*p)->name))
        {
             break;
        }
    }
    return p;
    };

最近经常提不起精神!人家说种瓜得瓜,我这看的啥用哦!

阅读(1243) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:usb驱动

给主人留下些什么吧!~~