Ric*_*ard 3 c typedef structure
代码没有typedef(并且有效):
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用typedef双链接列表中的"节点"结构编写代码,但这不起作用:
typedef struct {
int data;
Node *next;
Node *prev;
} Node;
Run Code Online (Sandbox Code Playgroud)
有没有办法解决这个问题typedef?
您可以使用结构的前向声明
typedef struct sNode Node; // this is a typedef and a declaration of the struct
struct sNode{
int data;
Node *next;
Node *prev;
};
Run Code Online (Sandbox Code Playgroud)
这种方式Node是已知的(但未定义),在你的定义中struct.
这可以像Yunnosch一样压缩.但是,您需要struct Name在声明中使用表示法.
这样就可以使用typedefed名称,如果你的结构中有一些循环依赖,前向声明也是必要的.
也可以使用struct name作为typedef:
typedef struct Node Node;
struct Node{
int data;
Node *next;
Node *prev;
};
Run Code Online (Sandbox Code Playgroud)
我个人更喜欢第一种风格,对我来说似乎"更清晰",但第二个例子没有任何问题,只要编译器不是来自预标准时代(1989年之前).
正如Jens Gustedt指出的那样,如果第一种风格包含在C++中,那么它可能是不兼容的.
所以也许我应该改变我对第一个的偏好.
在typedef中,尚未知道要定义的类型,因此您需要引入并使用struct标记:
typedef struct Node_tag {
int data;
struct Node_tag *next;
struct Node_tag *prev;
} Node;
Run Code Online (Sandbox Code Playgroud)