c - Linux 中的红黑树

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

我正在从事一个涉及使用 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

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

最佳答案

你应该将你的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* .所以有不兼容指针类型的警告。

关于c - Linux 中的红黑树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006645/

相关文章:

linux - 使用 Rtlinux 命令运行可执行文件与使用 FIFO 策略调度进程/线程之间的区别

pointers - 隐藏 nil 值,理解为什么 golang 在这里失败

链表删除元素函数的C实现

linux - simple_read_from_buffer/simple_write_to_buffer 与 copy_to_user/copy_from_user

c - 为什么我的 .c 编码不能在 GCC 中编译?

c - void *的双指针和单指针?

linux - 如何修改 Linux 内核以更改 uname 返回的版本字符串?

c - 使用 scanf() 读取整数以在 for 循环中使用

python - ctypes - 查看返回结构的 c_char_p 字段

c - 寻找最大的 gcd while 循环问题