第八章 结构体
完结散花,C语言全部章节更新完毕
文章目录
1.初识
1.1为什么要用结构体
整型数,浮点型数,字符串是分散的数据表示,有时候我们需要用很多类型的数据来表示一个整体,比如学生信息
类比与数组:数组是元素类型一样的数据集合。如果是元素类型不同的数据集合,就要用到结构体了。
1.2定义一个结构体
它算是一个模板,一般不给赋具体的值,每一项在实际应用中并不是都要使用。
成员列表——也称为域表——每个成员都是结构体中的一个域
在声明的同时,定义变量,尽量少用
1.3初始化一个结构体变量并引用
//初始化结构体
#include <stdio.h>
#include <string.h>
struct Student
{
int num;
char name[32];
char sex;
int age;
double score;
char addr[32];
}; //注意这里的分号不要丢
int main()
{
int a;
//struct Student (这里可以看做 int) stu1(这个就属于a,变量名)
struct Student stu1 = {
2,"张三",'g',17,99.5,"北京"};//01
//001.那么如何赋值呢?两种赋值方式 1.int a=10 2.int a; a=10;对比以前的
struct Student stu2;//02
stu2.num = 2;//1.点运算符来访问结构体中的成员变量(域)
stu2.age = 18;//2.结构体里面的成员变量不是非要用上的,只用一部分也是可以的
stu2.score = 88.8;
strcpy(stu2.name,"李四");
strcpy(stu2.addr,"湖南");
//002.那么如何去引用呢?
printf("学号:%d,年龄:%d,分数:%.2f,名字:%s,地址:%s\n",stu2.num,stu2.age,stu2.score,stu2.name,stu2.addr);
return 0;
}
1.4例题
例题:输入两个学生的名字,学号,成绩,输出成绩高的学生的信息
重点认知:结构体没什么特殊的,只是把变量藏在结构体里面,而内部的变量,以前学习的东西是通用的,只是“触达的方式”不同
#include <stdio.h>
#include <string.h>
struct Student
{
int num;
char name[32];
char sex;
int age;
double score;
char addr[32];
};
int main()
{
int a;
//int tmp;
struct Student stu1 = {
2,"张三",'g',17,9,"北京"};//01
struct Student stu2;//02
struct Student max;//注意要把这个定义出来
stu2.num = 2;
stu2.age = 18;
stu2.score = 88.8;
strcpy(stu2.name,"李四");
strcpy(stu2.addr,"湖南");
max = stu1;//做一个变量的话,可以省写很多,要不然两个需要一一打印
if(stu1.score<stu2.score){
max = stu2;
}
printf("学号:%d,年龄:%d,分数:%.2f,名字:%s,地址:%s\n",
max.num,max.age,max.score,max.name,max.addr);
return 0;
}
2.结构体数组
#include <stdio.h>
#include <string.h>
struct Student
{
int num;
char name[32];
char sex;
int age;
double score;
char addr[32];
};
int main()
{