资源描述:
《最新C语言程序设计——结构体和共用体(完整版)教学讲义ppt.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C语言程序设计——结构体和共用体(完整版)问题:有时需要将不同类型的数据组合成一个有机的整体,以便于引用。如:一个学生有学号/姓名/性别/年龄/地址等属性intnum;charname[20];charsex;intage;intcharaddr[30];100101LiFunM1887.5Beijingnumnamesexagescoreaddr§12.2结构体的定义结构是一种构造数据类型(“结构”是由若干个成员组成的),在使用之前必须先定义,然后才能用来定义相应的结构体变量、结构体数组、结构体指针变量。结构体类型一般形式:struct结
2、构体名{成员列表};其中各成员都应进行类型说明,即类型名成员名;结构体变量的定义(3)直接定义结构体类型变量例:struct{intnum;charname[20];floatscore;}stu1,stu2;结构体变量的引用一般对结构体变量的使用,包括赋值、输入、输出、运算等都是通过其成员来实现的。结构体变量成员的表示方法:结构体变量名.成员名例:stu1.num(学生1的学号)stu1.score(学生1的分数)结构体变量的初始化和其他类型变量一样,定义结构体变量的同时,给它的成员赋初值。例:#includevoidm
3、ain(){structstudent{intnum;charname[20];floatscore;}stu1={1301,”ZhangSan”,82.50};printf(“No.%d,Name:%s,Score:%f”,stu1.num,stu1.name,stu1.score);}结构体变量的赋值通过输入语句或赋值语句,实现对结构体变量的成员赋值。例:#includevoidmain(){structstudent{intnum;charname[20];floatscore;}stu1;stu1.num=13
4、01;stu1.name=”ZhangSan”;scanf(“%f”,&stu1.score);printf(“No.%d,Name:%s,Score:%f”,stu1.num,stu1.name,stu1.score);}嵌套的结构体一个结构体的成员又是一个结构体。例:structdatestructstudent{intmonth;{intnum;intday;charname[20];intyear;charsex;}intage;structdatebirthday;charaddr[30];};birthdaynumnames
5、exageaddrmonthdayyear§12.3结构体数组结构体数组的每一个元素都是具有相同结构类型的结构体变量。例:structstudent{intnum;charname[20];floatscore;}stu[3];其中,定义了一个结构体数组stu,共有3个元素,每个元素都具有structstudent的结构形式。结构体数组的初始化赋值例:structstudent{intnum;charname[20];floatscore;}stu[3]={{1301,”ZhangSan”,57},{1302,“LiSi”,82.50},{
6、1303,“WangWu”,69}};当对全部元素进行初始化赋值时,也可以不给出长度。§12.4结构体指针变量12.4.1指向结构体变量的指针一般形式为:struct结构名*结构体指针变量名;例:structstudent{intnum;charname[20];floatscore;};structstudent*pstu;其中定义了一个指向student的指针变量pstu。12.4.1指向结构体变量的指针变量用结构体指针变量,访问结构体变量的各个成员,一般形式为:(*结构体指针变量).成员名;或结构体指针变量->成员名;例:(*pstu
7、).num或pstu->num例:#includevoidmain(){structstudent{intnum;charname[20];floatscore;}stu1={1301,”ZhangSan”,82.50},*pstu;pstu=&stu1;printf(“No.%d,Name:%s,Score:%f”,stu1.num,stu1.name,stu1.score);printf(“No.%d,Name:%s,Score:%f”,(*pstu).num,(*pstu).name,(*pstu).scor
8、e);printf(“No.%d,Name:%s,Score:%f”,pstu->num,pstu->name,pstu->score);}12.4.2指向结构体数组的指针变