zoukankan      html  css  js  c++  java
  • container_of用法及实现

    container_of 有的情况下,只知道 struct结构中莫个成员的指针,而需要知道整个struct的指针 (如网卡驱动里面,list)
    struct DDD {
            int a;
            int b;
            int c;
            int d;};struct DDD  ddd;
    |------------|  <-------  得到这个
    |      a         |
    |------------|
    |      b         |
    |------------|
    |      c         |  <-------  已知这个
    |------------|
    |      d         |
    |------------|
    
    
    //得到成员在结构
    #define offsetof(TYPE, MEMBER) ((unsigned int) &((TYPE *)0)->MEMBER)
    #define container_of(ptr, type, member) ({                      
            const typeof(((type *)0)->member) * __mptr = (ptr);     
            (type *)((char *)__mptr - offsetof(type, member)); })
    
    int main()
    {
       printf("ddd  is %p and ddd.c is %p 
    ",&ddd,&ddd.c);
       struct DDD * p= container_of(&ddd.c,struct DDD,c);
       printf("calc p is %p  
    ",p); 
       return 0;
    }
    /*
    output:
    ddd  is   0x601030 and ddd.c is 0x601038 
    calc  p is 0x601030 
    结果与想象
    */
    
  • 相关阅读:
    Java中替换字符串中特定字符,replaceAll,replace,replaceFirst的区别
    牛客剑指offer 67题(持续更新~)
    从尾到头打印链表
    字符串变形
    缩写
    删除公共字符
    替换空格
    二维数组的查找
    acm博弈论基础总结
    acm模板总结
  • 原文地址:https://www.cnblogs.com/pangblog/p/3315594.html
Copyright © 2011-2022 走看看