加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux内核链表实现的list_entry()中的(char *)强制转换

发布时间:2020-12-13 23:05:25 所属栏目:Linux 来源:网络整理
导读:这是宏定义: /** * 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,typ
这是宏定义:

/**
 * 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中减去成员的偏移量吗?像这样:

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

谢谢!

解决方法

不.指针算术相当于:

ptr[addend]

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

后者需要显式转换为char *(因为这是内存的单位)来直接操作指针的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读