文档详情

C语言程序设计(第六章).pptx

发布:2017-05-25约2.03万字共120页下载文档
文本预览下载声明
第6章 用户定制数据类型及位运算;6.1 结构;6.1.1 概述;1.定义一个结构的一般形式为: struct 结构类型名 { 成员表 }; 成员表由若干个成员组成,每个成员都是该结构的一个组成部分。对每个成员也必须作类型说明,其形式为: 类型说明符 成员名; ;2.结构类型变量的定义;(1)先定义结构类型,再说明结构变量。 这种定义一个结构变量的一般形式如下: struct 结构类型名 { 成员表列 }; /*这里需要“;” */ struct 结构类型名 结构变量表; 上面结构变量表中不同结构变量之间用逗号“,”隔开,例如: struct ST /* 定义结构类型 */ { int num; /* 学号 */ char *name; /* 姓名 */ char sex[3]; /* 性别 */ float score; /* 成绩 */ }; struct ST boy, girl; /* 定义结构变量 */;(2)在定义结构类型的同时说明结构变量。 这种定义一个结构变量的一般形式如下: struct 结构类型名 { 成员表 } 结构变量表; 例如: struct ST /* 定义结构类型 */ { int num; /* 学号 */ char *name; /* 姓名 */ char sex[3]; /* 性别 */ float score; /* 成绩 */ } boy, girl; /* 定义结构类型变量 */ 上面的定义与第一种方法相同,也定义了两个变量boy和girl为ST结构类型。;(3)直接说明结构变量 这种定义一个结构变量的一般形式如下: struct { 成员表 } 结构变量表; 例如: struct { int num; /* 学号 */ char *name; /* 姓名 */ char sex[3]; /* 性别 */ float score; /* 成绩 */ } boy, girl; /* 定义结构类型变量 */ 第三种方法与第二种方法的区别在于第三种方法中省去了结构类型名,而是直接给出结构变量。; 结构体内的成员也可以是另外一个结构,即构成了嵌套的结构类型。;6.1.3 结构类型变量的引用;例6.1 试编写为结构变量赋值并输出其值的程序。 int main(void) /* 主函数main() */ { struct DateType /* 定义结构类型 */ { int year; /* 年份 */ int month; /* 月份 */ int day; /* 日 */ }; struct StudentType /* 定义结构类型 */ { int num; /* 学号 */ char *name; /* 姓名 */ char sex[3]; /* 性别 */ struct DateType birthday; /* 生日 */ float score; /* 成绩 */ };; struct StudentType student; /* 定义结构类型变量 */ /* 为结构变量student赋值 */ student.num = 10101; /* 为num赋值 */ student.name = 刘杰明; /* 为name赋值 */ strcpy(student.sex, 男); /* 为sex复制赋值 */ student.birthday.year = 1968; /* 为year赋值 */ student.birthday.month = 6; /* 为month赋值 */ student.birthday.day = 18; /* 为day赋值 */ student.score = 98.8; /* 为score赋值 */ /* 输出结构变量student */ printf(学号:%d\n, student.num); /* 输出num */ printf(姓名:%s\n, student.name); /* 输出name */ printf(性别:%s\n, student.sex); /* 输出sex */ printf(生日:%d年,%d月,%d日\n, /* 输出birthday */ student.birthday.year, student.birthday.month, st
显示全部
相似文档