我书中的图形邻接表代码由:
typedef struct vertexNode //vertexNode in an AdjacencyList
{
VertexType data;
EdgeNodeType *firstEdgeNode;
} VertexNode, AdjList[MAXVEX];
AdjList adjList; # adjList is an MAXVEX-size array
我对typedef的最后一行感到困惑:typedef struct{...} AdjList[MAXVEX]
。
我能理解的书写方法是:
typedef struct{
...
} VertexNode,
VertexNode AdjList[MAXVEX]; # AdjList is an MAXVEX-size array
或
struct{
...
} AdjList[MAXVEX]; # AdjList is an MAXVEX-size array
从语法上讲,typedef
实际上是一个存储类,例如static
或extern
,并且类型别名声明的读取方式类似于变量声明。例如:
int x;
x
声明为int
类型的变量,而
typedef int x;
声明x
为类型别名,表示int
。
类似地,
struct vertexNode {
...
} VertexNode;
将VertexNode
声明为struct vertexNode
变量,但添加typedef
使其成为struct vertexNode
的别名。请注意,struct vertexNode { ... }
(整个对象)是一种类型,就像int
一样。它首先定义struct vertexNode
,然后引用它。
此外,当使用逗号时,数组声明的行为可能看起来很奇怪:
int x, y[5];
声明x
为int
,同时声明y
为5
int
s的数组。 (函数和指针也是如此。)此网站上还有其他问题。
将所有内容放在一起,如果您拿走typedef
,您的问题将像这样:
struct vertexNode
{
VertexType data;
EdgeNodeType *firstEdgeNode;
} VertexNode, AdjList[MAXVEX];
这将声明类型struct vertexNode
,类型VertexNode
的变量struct vertexNode
和AdjList
MAXVEX
s的数组struct vertexNode
。添加typedef
意味着VertexNode
成为struct vertexNode
的别名,并且AdjList
成为MAXVEX
struct vertexNode
s数组的别名。就个人而言,我不建议这样写,但我想它很简洁。
这是示例代码。
#include <stdio.h>
typedef char STR[1024];
int main() {
STR a = "1234"; // == char a[1024]
printf( "%s\n", a );
return 0;
}
我写了一个数据类型为char
的示例。您可以将其替换为任何类或结构。
所以..您的代码..
[AdjList a
与VertexNode a[MAXVEX]
相同