gpt4 book ai didi

c - 在结构内部声明结构时指向结构的指针

转载 作者:行者123 更新时间:2023-12-04 11:11:01 25 4
gpt4 key购买 nike

我有一个关于结构定义和指针的问题。

在链表节点结构的定义中我们定义结构如下:

typedef struct node
{
int data;
struct node *next;
}Node;

为什么我们要使用这种声明方式而不是:

typedef struct node
{
int data;
struct node next; //changed this line
}Node;

提前致谢!

最佳答案

结构在其右大括号之后定义。直到它的结构具有不完整的类型。但是结构的定义要求除灵活数组之外的所有成员都必须具有完整的类型。

所以在这个声明中

typedef struct node
{
int data;
struct node next; //changed this line
}Node;

下一个数据成员的类型不完整。

来自 C 标准(6.7.2.1 结构和 union 说明符)

  1. ...The type is incomplete until immediately after the } that terminates the list, and complete thereafter.

3 A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

至于指针,它们总是有完整的类型,因为它们的大小是已知的。

关于c - 在结构内部声明结构时指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498748/

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