Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2306259
  • 博文数量: 141
  • 博客积分: 3552
  • 博客等级: 中校
  • 技术积分: 4148
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-15 14:39
个人简介

熟悉Linux下程序设计及各种应用程序 熟悉C Language 熟悉Glusterfs、FFmpeg、CDN 系统设计,计算机图形系统设计、分布式程序设计 目前主要研究方向:流媒体

文章分类

全部博文(141)

分类: C/C++

2009-08-12 16:18:53

通过结构体的成员获得结构体的地址,摘自kernel的一段宏,为了理解container_of,写了个例子


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
     const typeof( ((type *)0)->member ) *__mptr = (ptr); \
     (type *)( (char *)__mptr - offsetof(type,member) );})

struct example{
unsigned char ea;
int eb;
int ec;
};

int main()
{
        struct example *example=malloc(sizeof(struct example));
        memset(example,0,sizeof(struct example));
        printf("%p\n",example);
        printf("%p\n",&(example->ec));
        printf("%p\n",(void *)offsetof(struct example,ec));
        printf("%p\n",container_of(&(example->ec),struct example,ec));
        free(example);
        example=NULL;
        return 0;
}

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

上一篇:tar打包原理分析

下一篇:objcopy用法

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