《C语言》-(结构体:struct)
结构体(构造类型)
结构体和数组的区别:
数组:只能由多个相同类型的数据构成;
结构体:可以有多个不同类型的数据构成;
一、结构体的定义:(2步)
1.定义结构体类型
struct Person
{ // 里面的3各变量,可以称为结构体的成员或者属性
int age;
double height;
char *name;
};
2.根据结构体类型,定义结构体变量
struct Person p = {20, 1.55, "jack"};
p.age = 30;
p.name = "rsoe";
struct Person p2 = {.height = 1.63, .age = 23, .name = "jim"};
-
错误写法:只有在定义结构体变量时才能一次性赋值
struct Person p3;
p3 = {25, 1.72, "jake"}; // 只有在定义结构体变量时才能一次性赋值
二、结构体变量的内存分析
1.定义结构体类型(并不会分配存储空间)
struct Date
{
int year;
int month;
int day;
};
2.根据结构体类型定义结构体变量(会真正分配存储空间)
struct Date d1 = {2014, 4, 10};
3.内存图示:
三、定义结构体变量的3种方式
1.先定义结构体类型,再定义结构体变量(分开定义)
例:
struct Student
{
int age;
int no;
};
struct Student stu;
2.定义结构体类型的同时定义结构体变量
例:
struct Student
{
int age;
int no;
} stu;
3.定义结构体类型的同时定义结构体变量(神略类型名称)
例:
struct
{
int age;
int no;
} stu;
// 注意:此方式不允许重复使用
四、结构体的作用域
1.定义在函数外部:
全局有效(从定义结构体类型的那行代码开始到文件结尾)
2.定义在函数(代码块)内部:
局部有效(从定义结构体类型的那行代码开始到代码块结束)
3.代码练习:
五、结构体数组
六、指向结构体的指针
1.定义:
struct Student *p;
2.访问结构体成员的三种方式
- 直接访问:
变量.属性; 如:stu.age;
- 间接访问:
1.(*p).属性;
2.p->属性
3.代码练习:
运行结果:
七、结构体的嵌套使用
/*情景: 一个学生含有学号、生日(年月日)、入学时间(年月日)等很多时间的属性是可以将年月日抽取成一个结构体 并在这个学生内部定义不同的结构体变量 */ #include <stdio.h> int main() { struct Date // 抽取出的日期结构体 { int year; int month; int day; }; struct Student // 结构体的嵌套使用 { int no; struct Date birthday; // 定义一个struct Date类型的变量birthday 用来存储生日 struct Date ruXueDate; // 定义一个struct Date类型的变量ruXueDate 用来存储入学日期 }; struct Student stu = {1, {1990, 6, 9}, {2010, 9, 15}}; // 输出生日 printf("year = %d, month = %d, day = %d\n",stu.birthday.year, stu.birthday.month, stu.birthday.day); return 0; }
// 运行结果:year = 1990, month = 6, day = 9