如何定义包含指向本身就是一个typedef结构? [英] How to define a typedef struct containing pointers to itself?
问题描述
我写在C链表,下面的code再present我的节点定义。
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;
据我所知(或认为我这样做)的结构节点
同 typedef结构节点
不是。当然我的code编译和运行,因为它是应该,但是,我分配接下来
和 preV时<得到很多的警告/ code>(警告:从分配不兼容的指针类型)。我猜测,这与我在如何定义它们的节点结构做。
我上传的完整源这里
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
所以,如果这确实是问题,应该怎么定义接下来
和 $ P $光伏
里面的 typedef结构节点
?
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);
这样一来,图书馆的用户不容易接触到资料库的内部,即节点
结构的字段。
这篇关于如何定义包含指向本身就是一个typedef结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!