gpt4 book ai didi

c - 这些c struct声明之间的区别?

转载 作者:行者123 更新时间:2023-12-04 12:18:38 26 4
gpt4 key购买 nike

我有一个看起来像这样的代码:

struct point {
int a;
int b;
}


可以像这样进一步使用:

struct point p;
p.x = 10;
p.y = 5;


现在我知道这也可以这样写:

typedef struct{
int x;
int y;
} point;


并可用作 point p

当我开始学习链表时,混乱就开始了,这就是我看到的代码。

typedef struct node {
int val;
struct node * next;
} node_t;


我有一些问题:


如果我们可以简单地使用 typedef struct { ... } node定义结构,那么编写 typedef struct node {.....的用途是什么
代码末尾的 node_t确实令人困惑,因为据我所知,它已经定义了 node类型,因此我们可以调用 node x创建一个节点,那么 node_t的需求是什么,或者基本上是 }之后是什么意思?


这不行吗?

typedef struct {
int val;
struct node * next;
} node;

最佳答案

如果我们可以简单地使用typedef struct { ... } node定义结构,那么编写typedef struct node {.....的用途是什么

代码末尾的node_t确实令人困惑,因为据我所知,它已经定义了node类型,因此我们可以调用node x创建一个节点,那么node_t的需求是什么,或者基本上是}之后是什么意思?



在C语言中,结构可以同时具有标签和typedef名称。在结构声明中:

typedef struct node {
int val;
struct node * next;
} node_t;

node是标签, node_ttypedef名称。您可以使用标记或 typedef名称来声明结构变量。
struct node *new_node;   // OK  
node_t *head; // OK

实际上,标记和typedef名称甚至可以相同,尽管这不是必需的:
typedef struct node {
int val;
struct node * next;
} node;


这不行吗?

typedef struct {
int val;
struct node * next;
} node;

不行。这行不通。为什么?
原因是,当一个结构的成员指向同一种结构时,就像节点一样,我们需要使用一个结构标签。没有 node标记,我们将无法声明 next的类型。

建议阅读:由于Op正在寻求有关数据结构的良好资源。您可以在这里:

教程: Introduction to Data Structures
图书: Classic Data Structures

关于c - 这些c struct声明之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24386892/

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