如何定义包含指向自身的指针的 typedef 结构? [英] How to define a typedef struct containing pointers to itself?
问题描述
我正在用 C 编写一个 LinkedList,下面的代码代表我的 Node 定义.
I am writing a LinkedList in C, the below code represent my Node definition.
typedef struct {
int value;
struct Node* next;
struct Node* prev;
} Node;
我理解(或认为我知道)struct Node
与 typedef struct Node
不同.允许我的代码按预期编译和运行,但是,在分配 next
和 prev
时我收到很多警告(警告:从不兼容的指针类型分配).我猜这与我如何在 Node 结构中定义它们有关.我上传了完整的源代码这里
I understand (or think that I do) that struct Node
not the same as typedef struct Node
. Granted my code compiles and runs as it's supposed to, however, I get a lot of warnings when assigning next
and prev
(warning: assignment from incompatible pointer type). I am guessing that this has to do with how I'm defining them in the Node structure.
I uploaded the full source here
那么,如果这确实是问题所在,我应该如何在 typedef struct Node
中定义 next
和 prev
?
So, if that is indeed the problem, how should I define next
and prev
inside the typedef struct Node
?
我担心这可能是转帖,但找不到我要找的内容.谢谢.
I was worried this may be a repost, but couldn't quite find what I was looking for. Thanks.
推荐答案
你需要按照这个顺序进行:
You need to do it in this order:
typedef struct Node Node;
struct Node
{
int value;
Node *next;
Node *prev;
};
这并不完全符合您的要求,但它解决了问题,并且通常是这样做的.我认为没有更好的方法.
That doesn't do exactly what you asked, but it solves the problem and is how this generally is done. I don't think there's a better way.
这种前向声明还有第二个用途,即数据隐藏.如果列表是在库中实现的,则您可以在公共标头中只包含 typedef
以及如下函数:
This kind of forward declaration has a second usage, in data hiding. If the list was implemented in a library, you could have just the typedef
in the public header, along with functions like:
Node * list_new(void);
Node * list_append(Node *head, Node *new_tail);
size_t list_length(const Node *head);
通过这种方式,库的用户无法轻松访问库的内部,即 Node
结构的字段.
This way, users of the library don't have easy access to the internals of your library, i.e. the fields of the Node
structure.
这篇关于如何定义包含指向自身的指针的 typedef 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!