C语言 如何定义包含指向自身的指针的 typedef 结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3988041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:45:47  来源:igfitidea点击:

How to define a typedef struct containing pointers to itself?

cstructtypedef

提问by Kenny Cason

I am writing a LinkedList in C, the below code represent my Node definition.

我正在用 C 编写一个 LinkedList,下面的代码代表我的 Node 定义。

typedef struct {
    int value;
    struct Node* next;
    struct Node* prev;
} Node;

I understand (or think that I do) that struct Nodenot 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 nextand 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

我理解(或认为我知道)这struct Nodetypedef struct Node. 允许我的代码按预期编译和运行,但是,在分配nextand时我收到很多警告prev(警告:从不兼容的指针类型分配)。我猜这与我如何在 Node 结构中定义它们有关。我在这里上传了完整的源代码

So, if that is indeed the problem, how should I define nextand previnside the typedef struct Node?

那么,如果这确实是问题所在,我应该如何定义nextprevtypedef struct Node?

I was worried this may be a repost, but couldn't quite find what I was looking for. Thanks.

我担心这可能是转帖,但无法完全找到我要找的东西。谢谢。

回答by unwind

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.

这并不完全符合您的要求,但它解决了问题,并且通常是这样做的。我不认为有更好的方法。

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 typedefin the public header, along with functions like:

这种前向声明还有第二个用途,即数据隐藏。如果列表是在库中实现的,则可以typedef在公共标题中只包含 ,以及以下功能:

Node * list_new(void);
Node * list_append(Node *head, Node *new_tail);
size_t list_length(const Node *head);

This way, users of the library don't have easy access to the internals of your library, i.e. the fields of the Nodestructure.

这样,库的用户就无法轻松访问库的内部,即Node结构的字段。

回答by Arun

Another acceptable way and with the least change to OP's code is the following:

另一种可接受的方式和对 OP 代码改动最少的方法如下:

typedef struct NodeT {
    int value;
    struct NodeT * next;
    struct NodeT * prev;
} Node;

Note the introduction of NodeTand its usage in nextand prevuntil Nodeis available.

请注意NodeTinnextprevuntil的介绍及其用法Node可用。