(unsigned int)(&(((type *)0)->member)) 的作用

(unsigned int)(&(((type *)0)->member))是一个用于计算结构体成员偏移量的宏定义。
它的作用是将一个空指针强制转换为指向结构体的指针,然后取该结构体中某个成员的地址,
最后将该地址转换为无符号整型。这个宏定义通常用于实现Linux内核中的双向链表。具体来说,
它可以通过给定一个结构体指针和结构体中某个成员的名称,计算出该成员相对于结构体基地址的偏移量,从而实现在双向链表中快速定位结构体的功能。

举个例子,假设有如下定义的结构体:
```c
struct student {
    int id;
    char name[20];
    int age;
};
```
那么,`(unsigned int)(&(((struct student *)0)->age))`就是计算出`age`成员相对于
`struct student`结构体基地址的偏移量。在这个例子中,`age`成员的偏移量为`24`,
因为`id`成员占用了`4`个字节,`name`成员占用了`20`个字节,而`age`成员紧随其后,
占用了`4`个字节。

struct test {
    short a; // 偏移 0 个字节,占用 2 个字节
    short b; // 偏移 2 个字节,占用 2 个字节
    int c; // 偏移 4 个字节,占用 4 个字节
    int d; // 偏移 8 个字节,占用 4 个字节
};
int main(void) {
 
    printf("a 偏移 %d 个字节, 占用 %d 个字节\n", (unsigned long) &((struct test *)0)->a, (unsigned long) sizeof(((struct test *)0)->a));
    printf("b 偏移 %d 个字节, 占用 %d 个字节\n", (unsigned long) &((struct test *)0)->b, (unsigned long) sizeof(((struct test *)0)->b));
    printf("c 偏移 %d 个字节, 占用 %d 个字节\n", (unsigned long) &((struct test *)0)->c, (unsigned long) sizeof(((struct test *)0)->c));
    printf("d 偏移 %d 个字节, 占用 %d 个字节\n", (unsigned long) &((struct test *)0)->d, (unsigned long) sizeof(((struct test *)0)->d));
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值