一、结构体的基本概念
● 数 组:只能由多个相同类型的数据组成
● 结构体:可以由多种不同类型的数据组成
代码练习:
#include <stdio.h>
int main()
{
// 1.定义结构体类型 struct person (并不会分配存储空间)
struct person
{
int age;
double height;
char *name;
};
//2.根据结构体类型,定义结构体变量 (真正分配存储空间)
struct person p ={20,1.55,"jack"};
p.age = 30; //修改结构体元素的值
p.name = "rose";
printf("age =%d,name = %s,height = %f
",p.age,p.height,p.name);
return 0;
}
二、结构体的三种定义方式
● 先定义类型,再定义变量
int main()
{
struct student
{
int age;
double height;
char *name;
};
struct student stu = {20,1.78,"jack"};
}
● 定义类型的同时定义变量
int main()
{
struct student
{
int age;
double height;
char *name;
}stu;
struct student stu2;
}
● 定义类型的同时定义变量(省略了类型名称)
int main()
{
struct {
int age;
char *name;
}stu;
}
三、结构体数组
#include <stdio.h>
//定义一个结构体数组,并且遍历结构体数组内各元素
int main()
{
int i;
struct RankRecord //定义结构体数据类型
{
int no;
char *name;
int score;
};
struct RankRecord record[3] = //定义结构体变量
{
{1,"jack",5000},
{2,"tom",3000},
{3,"jim",2000}
};
record[1].no = 5; //修改结构提内元素的赋值
//record[1] = {5,"tom",3000}; 错误写法
for(i = 0;i <3;i++){
printf("%d %s %d
",record[i]);
}
return 0;
}

四、结构体的作用域
1、定义在函数外部
全局有效(从定义结构体类型的那行代码开始到文件结尾)
2.定义在函数内部:
局部有效(从定义结构体类型的那行代码开始到代码块结束)
#include <stdio.h>
void test();
int main()
{
//struct person p; 报错,在test函数内部定义的结构体类型只能在test函数内部使用
rerurn 0;
}
void test()
{
struct person
{
int age;
double height;
};
}
五、指向结构体的指针
定义结构体指针
结构体类型 *p; 例:struct person *p;
p =&变量名; p =&stu;
#include <stdio.h> /*定义一个结构体变量,输出用指针指向该结构体的值,使用指针修改 这个结构体内的元素 */ int main() { struct person //定义结构体类型 { int age; int no; }; struct person stu ={10,5}; //赋值 struct person *p; p = &stu; //指向了stu变量 //三种方法可实现修改结构体内元素的值 stu.age = 20; (*p).age = 30; //使用指针修改结构体内元素的值 p->age = 40; //三种输出结构体内元素的值的方法 printf("%d %d ",stu.age,stu.no); printf("%d %d ",(*p).age,(*p).no); printf("%d %d ",p->age,p->no); return 0; }
六、结构体的嵌套使用
/*情景: 一个学生含有学号、生日(年月日)、入学时间(年月日)等很多时间的属性是可以将年月日抽取成一个结构体 并在这个学生内部定义不同的结构体变量*/ #include <stdio.h> int main() { struct Date //抽取的日期结构体 { int year; int month; int day; }; struct Student { int no; struct Date birtuday; //结构体的嵌套使用 struct Date ruxue; }; struct Student stu = {22,{1992,01,15},{1991,05,12}}; //输出生日 printf("year = %d,month = %d,day = %d ",stu.birtuday.year,stu.birtuday.month,stu.birtuday.day ); return 0; }