C语言中用户可自定义的数据类型框架
结构体就是一个可以包含不同数据类型的一个结构,它是一种可以自己定义的数据类型。
它的特点和数组主要有两点不同:
首先结构体可以在一个结构中声明不同的数据类型。
第二,相同结构的结构体变量是可以相互赋值的,而数组是做不到的,因为数组是单一数据类型的数据集合,它本身不是数据类型(而结构体是),数组名称是常量指针,所以不可以做为左值进行运算,所以数组之间就不能通过数组名称相互复制了,即使数据类型和数组大小完全相同。
结构体变量的定义
1.typedef的使用
在定义完结构体类型后声明变量时不用写“struct”
typedef struct student // typedef struct 结构体类型名 // 结构体类型名可以不写
{ // {
char nam[10]; //
chat name[20]; //
char sex; // 成员列表;
int age; //
float score[3]; //
float ave; //
}stu; // }stu; //stu==struct stu
stu stu1,stu2,stu[30]; // stu 结构体类型名 变量名列表; //不用写“struct”
2.先定义结构体类型再定义结构体变量:
struct student // struct 结构体类型名
{ // {
char nam[10]; //
chat name[20]; //
char sex; // 成员列表;
int age; //
float score[3]; //
float ave; //
}; // };
struct student stu1,stu2,stu[30]; // student 结构体类型名 变量名列表;
或在定义结构体类型的同时定义结构体变量:
struct student // struct 结构体类型名
{ // {
char nam[10]; //
chat name[20]; //
char sex; // 成员列表;
int age; //
float score[3]; //
float ave; //
}stu1,stu2,stu[30]; // }变量名列表;
3.直接定义结构体变量,无类型名。(不推荐使用)