typedef是类型定义的意思。typedef struct 是为了使用这个结构体方便。
具体区别在于:
若struct node{ }
这样来定义结构体的话。在定义 node 的结构体变量时,需要这样写:struct node n
;
若用typedef,可以这样写:typedef struct node{ } NODE
; 。在申请变量时就可以这样写:NODE n
;其实就相当于 NODE 是node 的别名。区别就在于使用时,是否可以省去struct这个关键字。
在c++中:
struct Student
{
int age;
char name[12];
}stu1;//stu1是一个变量
typedef struct Student2
{
int age;
char name[12];
}stu2;//stu2是一个结构体类型,即stu2是Student2的别名
使用时可以直接访问stu1.age
但是stu2则必须先定义 stu2 s2;
然后 s2.age=5;
结构体指针
typedef struct node *link
就表示用 link
代替 struct node *
也就是本来要定义变量如下的
struct node * p;
可以写成link p
,这样明显简洁很多。
例如:
在C++中使用链表时,定义一个节点的结构体
typedef struct list
{
int num,score;
char name[10];
struct list *next;//不能使用node *next,因为此时该结构体名称还是list
}node;
typedef node *link;