gpt4 book ai didi

c - 自引用结构声明

转载 作者:太空狗 更新时间:2023-10-29 16:06:53 25 4
gpt4 key购买 nike

以下声明有效。

struct node
{
int a;
struct node *next;
};

但是,当我们定义以下内容时,它会报错。

"error: field ‘next’ has incomplete type"

为什么会这样?

struct node
{
int a;
struct node next; /* Not a pointer */
};

最佳答案

struct node 中的

node 是一个“struct tag”,在您编写它时会创建一个“不完整类型”:此时未声明但未定义的 struct 变量。该类型在结构的最终 }; 之前不完整。

在 C 中,通过使用指向该类型的指针,甚至可以在完全定义之前引用不完整的类型。但是,您不能分配该类型的变量(实例),因为尚未定义实际的结构定义。 (它的工作方式与 C++ 中的抽象基类完全相同,如果您熟悉的话。)

所以当你写

struct node {
int a;
struct node *next;
};

struct node *next 行的意思是“这是一个指向结构节点的指针,尽管我还不知道该类型是如何定义的”。但是您不能在相同类型的结构定义中声明类型为 struct node 的变量,这仅仅是因为您不能在创建它之前使用它。

关于c - 自引用结构声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25802689/

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