用结构体理解 typedef [英] Understanding typedef with struct
问题描述
我很难理解这个代码示例:
I am getting a hard time understanding this sample of code:
typedef struct node
{
int data;
struct node * next;
} node;
typedef node * nodepointer;
所以,我们正在使用 typedef 构建结构节点......我假设我们这样做是为了在不需要struct"关键字的情况下初始化结构.
So, we are building the struct node using typedef... I assume we are doing this in order to initialize the struct without the "struct" keyword being necessary.
我想问一下为什么在结构定义中我们使用名称节点"两次(在开始和结束处).
I want to ask why in the struct definition we used the name "node" twice (at start and end).
其次是 typedef node * nodepointer;
指向什么.在这种情况下是否有必要使用 typedef?这个表达式 node * nodepointer;
不等于吗?
Secondly what typedef node * nodepointer;
points to. Is it necessary to use typedef in this case? Is this expression node * nodepointer;
not equal?
推荐答案
问题是您同时在做两件事:声明结构类型和将该结构类型定义为名称.
The question is that you are doing two things at once: declaring struct type and typedefing that struct to a name.
typedef
的语法是
typedef <some type> name;
其中某些类型可能是简单类型,例如 int
、long
等,也可能是复杂的类型,例如 struct foo
,而这不管 struct foo
之前是否已经声明过,或者在那个时候声明过.
where some type may be a simple type, like int
, long
, etc. or a complex one like struct foo
, and this regardless of wether struct foo
has been declared before or it's being declared at that very point.
所以
typedef struct foo { int bar; } foo;
对应
typedef <some type> name;
其中
是 struct foo { int bar;}
和 name
是 foo
where <some type>
is struct foo { int bar; }
and name
is foo
关于第二个问题,
在这种情况下,
是 node *
而 name
是 nodepointer
,所以>
In this case <some type>
is node *
and name
is nodepointer
, so
typedef node * nodepointer;
正在将 nodepointer
定义为指向 node
的指针(您之前已将其 typedefd 为 struct node { ... }
)
is typedefing a nodepointer
as a pointer to a node
(which you have typedefd just before to be a struct node { ... }
)
这篇关于用结构体理解 typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!