container_of小例

container_of小例, 仅供复习参考用

  1 #include <stdio.h>
  2 #include <linux/kernel.h>
  3 #include <string.h>
  4 #include <strings.h>
  5 
  6 #define offsetof(TYPE,MEMBER) ((int) &((TYPE *)0)->MEMBER)  
  7 //通过获取结构体中的某个成员的,反推该结构体的指针 
  8 #define container_of(ptr, type , member) ({ \
  9             const typeof(((type *)0)->member) *__mptr = (ptr) ; \
 10             (type *)((char *)__mptr - offsetof(type,member)) ;})
 11 
 12 
 13 typedef struct mystruct
 14 {
 15     int a;
 16     int b;
 17     char c;
 18 }TEST;
 19 
 20 int main(void)
 21 {
 22     TEST mytest;
 23     memset(&mytest, 0, sizeof(mytest));
 24     printf("&mytest = %p\n",&mytest);
 25     TEST* p = container_of(&mytest.c, TEST, c);
 26     printf("p = %p\n",p);
 27     printf("p->a = %d\n", p->a);
 28     printf("p->b = %d\n", p->b);
 29     printf("p->c = %d\n", p->c);
 30     return 0;
 31 }
root@ubuntu:/shiyan/shiyan271# gcc shiyan271.c
root@ubuntu:/shiyan/shiyan271# ./a.out
&mytest = 0xbf9c1d9c
p = 0xbf9c1d9c
root@ubuntu:/shiyan/shiyan271# gcc shiyan271.c
root@ubuntu:/shiyan/shiyan271# ./a.out
&mytest = 0xbff1a9ec
p = 0xbff1a9ec
p->a = 0
p->b = 0
p->c = 0
root@ubuntu:/shiyan/shiyan271# 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值