声明中第一个“节点”的目的是什么:“typedef struct node { – – – } Node;”?

我正在研究我教授的代码示例,以便更好地了解链接数据结构。

在我们的linked-list.c示例中,教授定义了一个类型Node,如下所示:

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

小写节点有什么意义? 我的印象是你可以写,例如:

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

然后使用Node作为自己的类型。 它是否与以下事实有关:如果您不包含小写节点,那么当编译器评估代码时,它将无法理解“struct node * next”的含义?

看看这个声明:

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

这可以合并为一个语句(简化声明):

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

它是否与以下事实有关:如果您不包含小写node那么当编译器评估代码时,它将无法理解“ struct node *next ”的含义?

是。

struct node中的struct node是struct类型的标记 。 如果你给struct一个标签,你可以从标签完成的那一刻起引用那个类型,所以在

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

struct node *next; 声明一个成员next ,它是一个指向正在定义的结构类型的指针。 typedef名称Node在之前不可用; 达到定义的结束。

如果省略标记,则在typedef完成之前不能以任何方式引用所定义的类型,因此在

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

line struct node *next; 使用next指向的标记node声明一个新的,不相关的,不完整的struct类型。

这是有效的,但是struct node任何内容都是已知的(除非它在其他地方被定义),所以你不能使用next指针而不将其转换为指向任何地方的完整类型的指针(不是无处不在, Node foo; foo.next = malloc(12);等仍然可以工作)。

他正在为节点定义一个临时名称,因为他正在使用一种众所周知的技术来避免在每个struct对象的声明上编写struct node

如果他愿意:

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

你将不得不使用:

 struct node* node; 

声明一个新节点。 为避免这种情况,您必须在以后定义:

 typedef struct node Node; 

为了能够声明如下对象:

 Node* node; 

到底:

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

只是struct node { ... };的快捷方式struct node { ... }; 除了typedef struct node Node;

这里struct node是一个类似int的类型

因此

 struct node { int data; struct node *next; }NodeVar; 

表示您正在声明struct node的单个变量Node。

比如int intVar;

typedef是为了使你的代码可以理解。

这样当你使用时

 typedef struct node Node; 

你可以使用相同的声明

 Node NodeVar; 

考虑以下代码:

 #include  typedef struct { int data; struct node *next; } Node; int main() { Node a, b = {10, NULL}; a.next = &b; printf("%d\n", a.next->data); } 

这不会编译。 编译器不知道struct node是什么,除了它存在。 因此,您可以将结构中的定义更改为Node *next; 。 typedef在声明之前不在范围内,因此它仍然无法编译。 简单的答案就是如他所说,在struct之后使用node标签,它工作正常。

小写“节点”是结构类型…即结构节点{stuff}是包含东西的节点结构。

另一方面,大写“Node”是一种全新的数据类型,它指的是“struct node”

通常(虽然在C ++中我认为你可以),你不能在C程序中传递“节点”…例如作为函数的参数。 相反,你必须传递一个’struct node’作为你的参数……

 // this will throw a syntax error because "node" is not a data type, // it's a structure type. void myFunc( node* arg ); // while this will not because we're telling the compiler we're // passing a struct of node void myFunc( struct node* arg ); // On the other hand, you *can* use the typedef shorthand to declare // passing a pointer to a custom data type that has been defined // as 'struct node' void myFunc( Node* arg );