在Linux的红色黑树

Gre*_*tle 2 c pointers red-black-tree linux-kernel

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

struct source_store{
    sector_t source;
    sector_t cache;
    struct rb_node * node;
}
Run Code Online (Sandbox Code Playgroud)

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

struct rb_node * parent = root->rb_node;
struct source_store * store = rb_entry(parent, struct source_store, node);
Run Code Online (Sandbox Code Playgroud)

但是,在编译时,我收到此错误:

warning: initialization from incompatible pointer type
Run Code Online (Sandbox Code Playgroud)

此外,当我从树中检索struts时,我在源和缓存字段中存储的数字是不同的.例如,我将数字512存储在源字段中,当我稍后检索结构时,它将是一些可笑的大数字,如16810075660910329857.根据我的理解,sector_t是一个长的无符号整数.为什么存储的数字会发生变化?为什么指针类型不兼容?

Nar*_*uil 6

你应该定义你struct source_store的:

struct source_store{
    sector_t source;
    sector_t cache;
    struct rb_node node; // not a pointer to node
}
Run Code Online (Sandbox Code Playgroud)

那是因为rb_entry被定义为

#define rb_entry(ptr, type, member) container_of(ptr, type, member)
Run Code Online (Sandbox Code Playgroud)

它只是一些简单的偏移计算

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

该类型的__mptrIS struct rb_node**和您的类型ptrstruct rb_node*.因此存在不兼容指针类型的警告.