【问题标题】:Red Black Tree in LinuxLinux中的红黑树
【发布时间】:2013-06-05 02:11:37
【问题描述】:

我正在开发一个涉及使用 rbtree.h 中定义的 rb_tree 的 Linux 内核项目。这是我存储在树中的结构:

struct source_store{
    sector_t source;
    sector_t cache;
    struct rb_node * node;
}

为了从树中检索对象,我执行以下操作:

struct rb_node * parent = root->rb_node;
struct source_store * store = rb_entry(parent, struct source_store, node);

但是,在编译时,我得到了这个错误:

warning: initialization from incompatible pointer type

此外,当我从树中检索 struts 时,我存储在源字段和缓存字段中的数字是不同的。例如,我将数字 512 存储在源字段中,当我稍后检索结构时,它会是一个非常大的数字,例如 16810075660910329857。据我了解,sector_t 是一个 long long 无符号整数。为什么存储的数字会改变?为什么指针类型不兼容?

【问题讨论】:

  • 如何将struct source_store 作为第二个参数传递 - 它是一种数据类型而不是变量。还有,rb_entry的原型是什么?
  • 根据本教程:lwn.net/Articles/184495,必须传入类型。原型为:rb_entry(pointer, type, member);其中 member 是包含结构中的节点的名称。 rb_entry 只是 container_of() 的包装器。
  • 那是因为rb_entry 是宏而不是函数。这就是为什么您需要在问题中提供此信息 - rb_entry 的定义。
  • @user93353 Linux 内核充满了这类宏。在我看来,当 linux-kernel 标签存在时,假设读者理解 Linux 内核的基本 API 是一个合理的假设。

标签: c pointers linux-kernel red-black-tree


【解决方案1】:

您应该将struct source_store 定义为:

struct source_store{
    sector_t source;
    sector_t cache;
    struct rb_node node; // not a pointer to node
}

那是因为rb_entry被定义为

#define rb_entry(ptr, type, member) container_of(ptr, type, member)

这只是一些简单的偏移量计算

#define container_of(ptr, type, member) ({             /
         const typeof( ((type *)0)->member ) *__mptr = (ptr);  /   <--error happens here
         (type *)( (char *)__mptr - offsetof(type,member) );})

__mptr 的类型是struct rb_node**,您的ptr 的类型是struct rb_node*。所以会有指针类型不兼容的警告。

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 2010-09-06
    • 2018-02-07
    • 1970-01-01
    • 2015-11-17
    • 2012-11-30
    • 2014-07-05
    • 2013-02-28
    • 2022-07-30
    相关资源
    最近更新 更多