c语言container理解

本文解析了C/C++中的rt_container_of宏和offsetof函数的工作原理,它们如何通过成员指针反推出结构体地址,以及typeof关键字在container_of宏中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看到一个宏定义如下:

/**
 * rt_container_of - return the member address of ptr, if the type of ptr is the
 * struct type.
 */
#define rt_container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))

因为程序中多次使用,所以对其进行了详细分析,过程如下:

这个宏的作用就是通过一个结构体的某个成员的指针,反推出这个结构体的首地址。这种操作非常有用,尤其在C语言中写面向对象的程序时,相当模拟了C++多态的效果。先写个小程序做个实验,验证一下(&((type *)0)->member)到底是什么结果:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
typedef struct {

    char a;
    char b;
    char c;
    char d;
}test_t;

void main(void)
{
    printf("offsetof: %d\n", offsetof(test_t, a));
    printf("offsetof: %d\n", offsetof(test_t, b));
    printf("offsetof: %d\n", offsetof(test_t, c));
    printf("offsetof: %d\n"

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值