一、结构体的意义
问题:学籍管理需要每个学生的下列数据:学号、姓名、性别、年龄、分数,请用C语言程序存储并处理一组学生的学籍。
单个学生学籍的数据结构
•学号(num):int型
•姓名(name):char [ ] 型
•性别(sex):char型
•年龄(age):int型
•分数(score):float型
思考:如果有多个学生,该怎么定义已学数据类型无法解决。
二、结构体的概述
正式:结构体是由一批数据组合而成的结构型数据。组成结构型数据的每个数据称为结构型数据的“成员” ,其描述了一块内存区间的大小及解释意义
通俗:结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
三、结构体的定义
语法:
struct 结构体名
{
结构体成员列表
};
四、结构体的使用
struct 结构体名 变量名
struct 结构体名 变量名 = {成员1值,成员2值..}
定义结构体时顺便创建变量
#include <stdio.h>
#include <string.h>
//结构体的定义
struct student
{
int num; //学号
char name[16]; //姓名
float score; //成绩
}stu5 = {1002,"lihua",89},stu6; //3.定义结构体时顺便定义变量
int main(int argc, const char *argv[])
{
//1.定义完结构体变量再进行赋值
struct student stu1;
stu1.num = 1000;
strcpy(stu1.name,"zhangsan");
//stu1.name = "zhangsan"; //错误行为
stu1.score = 98;
printf("num = %d, name = %s, score = %f\n", stu1.num, stu1.name, stu1.score);
//2.定义结构体变量时进行赋值
struct student stu2 = {1001, "lisi", 99};
printf("num = %d, name = %s, score = %f\n", stu2.num, stu2.name, stu2.score);
struct student stu3 = {1001, "lisi"};
printf("num = %d, name = %s, score = %f\n", stu3.num, stu3.name, stu3.score);
struct student stu4 = {
.num = 1001,
.score = 99,
};
printf("num = %d, name = %s, score = %f\n", stu4.num, stu4.name, stu4.score);
printf("num = %d, name = %s, score = %f\n", stu5.num, stu5.name, stu5.score);
stu6.num = 1004;
strcpy(stu6.name,"zhangsan2");
stu6.score = 70;
printf("num = %d, name = %s, score = %f\n", stu6.num, stu6.name, stu6.score);
return 0;
}
五、结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名[元素个数] = {{},{},……{}}
#include <stdio.h>
#include <string.h>
//定义结构体
struct student
{
int num;
char name[16];
float score;
};
int main(int argc, const char *argv[])
{
struct student stu[3] = {{1000, "zhangsan", 99}, {1001, "lisi", 89}, {1003, "zhouwu", 79}};
struct student stu1[3];
int i;
stu1[0].num = 2000;
strcpy(stu1[0].name, "lihua");
stu1[0].score = 100;
printf("num = %d, name = %s, score = %f\n", stu1[0].num, stu1[0].name, stu1[0].score);
for (i = 0; i < 3; i++)
{
printf("num = %d, name = %s, score = %f\n", stu[i].num, stu[i].name, stu[i].score);
}
return 0;
}