typedef struct 与 struct
时间: 2023-10-23 12:45:54 浏览: 43
typedef 是 C 语言中的一个关键字,用于定义新的数据类型。它的语法格式为:
typedef 旧类型名 新类型名;
此时,新类型名就可以作为旧类型名的别名使用,可以避免在代码中多次使用旧类型名时出现的冗长和混乱。例如:
typedef unsigned char byte;
这样,以后就可以用 byte 代替 unsigned char。
而 struct 则是 C 语言中用于定义结构体的关键字。结构体是一种自定义的数据类型,可以将不同类型的变量打包在一起,形成一个新的数据类型。例如:
struct student {
char name[20];
int age;
float score;
};
这个结构体定义了一个名为 student 的新类型,包含了一个字符串类型的 name,一个整型的 age,和一个浮点型的 score。可以通过以下方式声明和使用该结构体类型的变量:
struct student stu;
stu.age = 18;
strcpy(stu.name, "Tom");
stu.score = 90.5;
也可以使用 typedef 将结构体类型定义为新的数据类型名,例如:
typedef struct student {
char name[20];
int age;
float score;
} Student;
这样,以后就可以用 Student 代替 struct student。例如:
Student stu;
stu.age = 18;
strcpy(stu.name, "Tom");
stu.score = 90.5;