为什么要用到结构体?
需要将不同类型的数据组合成一个有机的整体,以便于引用。
例如:一个学生有学号,姓名,性别,年龄等属性;
注意:
- 不能将一个结构体变量作为一个整体机型输入和输出
- 结构体变量的地址主要作用于函数参数,传递结构体变量的地址
1. 定义
struct 结构体名{
成员列表
};
例如:
struct student{
int ID;
char name[20];
int age;
};
1.1 定义结构体类型变量的方法
1 先声明结构体类型再定义变量
//定义结构体类型
struct student{
int ID;
char name[20];
int age;
};
//定义2个结构体变量
struct student stu1, stu2;
在定义了结构体变量后,系统会为它分配内存单元。
2 在声明类型的同时定义变量
//stu1, stu2为定义的结构体变量
struct student{
int ID;
char name[20];
int age;
}stu1, stu2;
3 直接定义结构体类型变量
这里结构体名可有可无
struct {
int ID;
char name[20];
int age;
}stu1, stu2;
4 定义结构体数组
struct student{
int ID;
char name[20];
}stus[3];
或者
struct student stus[3];
初始化结构体数组:
定义数组时初始化:
struct student str[]{{1, '李华'}, {2, '小明'}}
或者后续使用循环赋值;
1.2 结构体指针
声明结构体变量指针的一般形式:
struct 结构体名* 结构体指针变量名;
eg:
struct student{
int ID;
char name[20];
};
struct student stu = {1, '小明'};
struct student* pstu;
pstu = &stu;
访问结构体指针变量:
(*pstu).name;
pstu->name;