gpt4 book ai didi

c - queue.h库中struct的使用

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:40 37 4
gpt4 key购买 nike

我目前正在研究 C 语言中宏的使用。为了习惯它们并学习,我正在查看允许在 C 中创建动态数据结构的 queue.h 库。

你可以在这里找到来源:bxr.su/OpenBSD/sys/sys/queue.h

现在我偶然发现了以下定义:

#define SLIST_ENTRY(type) \
struct { \
struct type *slh_next;
}

如果我没记错的话,这将创建一个结构,该结构的指针将指向单向链表中的下一个元素。我只是想不通,为什么你必须创建结构。仅仅指针还不够吗?

#define SLIST_ENTRY(type) \
struct type *slh_next

我想如果你想创建一个双向链表,你会创建一个带有 next 和 before 指针的结构。那么这只是为了保持一致,还是 SLIST 定义中的结构体有特定用途?

PS:如何在移动设备上格式化代码和链接?

最佳答案

当您在单链表中使用它时可能没有多大意义,但如果您在 source code 中看到(双链)列表的定义那么它的目的就更清楚了,因为现在它有两个指针,您只需将一个 LIST_ENTRY 结构添加到您的数据结构中即可。

#define LIST_ENTRY(type)                                             \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}

LIST_ENTRY(type) 扩展为匿名 struct。在 C11 标准中,匿名 struct 与匿名 union 一起被引入。当匿名 struct 或匿名 union 包含在另一个 structunion 中时,封闭结构获取字段封闭的匿名结构。

看看这个questionexample code :

struct entry { 
...
LIST_ENTRY(entry) entries;
...
} *n1, *n2, *np;

在这种情况下,LIST_ENTRY(entry) 的字段成为entry 的字段。是的,正如上面有人所说,这是一种通用类型的链接。现在一个函数可以像这样从这个结构中获取上一个和下一个元素:

#define LIST_INSERT_AFTER(listelm, elm, field) do {                 \
if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
(listelm)->field.le_next->field.le_prev = \
&(elm)->field.le_next; \
(listelm)->field.le_next = (elm); \
(elm)->field.le_prev = &(listelm)->field.le_next; \
} while (0)

关于c - queue.h库中struct的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669780/

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