结构体定义
平常看C语言的程序时,见到结构体定义有些是使用typedef定义,有些是直接使用struct定义,感觉有点混乱,其实简单梳理下就很清楚了。
使用struct
struct Student{
unsigned int id;
char* name;
}Stu1, Stu2;
Student
是标识符
,或者叫标签(Tag),可以通过struct Student Stu1;
来定义这个结构体的变量。
Stu1, Stu2
是变量
,可以不写,也可以写一个或多个,甚至可以写成数组。不写的话后面用到的时候可以通过struct Student Stu1, Stu2;
来定义两个结构体变量。
实际的工作过程相当于以下代码
// 定义Student结构体
struct Student{
unsigned int id;
char* name;
};
// 定义两个Student结构体的变量Stu1, Stu2
struct Student Stu1, Stu2;
使用typedef
typedef struct Student{
unsigned int id;
char* name;
}Stu;
Student
的含义和使用struct定义出来的相同,可以不写。
Stu
是变量类型
,跟直接使用struct含义不同了,它实际上相当于struct Student
, 可以直接使用Stu stu1;
来定义这个结构体的变量。可以写一到多个。
使用typedef定义结构体相当于以下代码完成的工作:
// 定义Student结构体
struct Student{
unsigned int id;
char* name;
};
// 给Student结构体起个别名Stu
typedef struct Student Stu;
©raveh.net