gpt4 book ai didi

c - Linux Kernel链表实现的list_entry()中的(char *) cast

转载 作者:太空狗 更新时间:2023-10-29 15:30:16 24 4
gpt4 key购买 nike

这是宏定义:

/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

我不明白为什么 ptr 被强制转换为 (char *)。我不能只从 ptr 中减去 member 的偏移量吗?像这样:

#define list_entry(ptr, type, member) \
((type *)((ptr)-(unsigned long)(&((type *)0)->member)))

谢谢!

最佳答案

没有。指针算术等同于:

ptr[addend]

不是

(ptr_type *)((unsigned long)&ptr + addend)

后者需要显式转换为 char *(因为它是内存单元)以直接操作指针的值。

关于c - Linux Kernel链表实现的list_entry()中的(char *) cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8608583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com