文档介绍:本次课内容:1、结构体类型概述,2、结构体类型变量的定义和引用。教学目的:掌握结构体类型的相关概念,掌握结构体变量的定义和引用。重点:结构体概念、定义和引用。难点:结构体成员的引用。预录、结构体。如:一个学生的情况描述需多种数据类型(一个记录),一个数组又只能存放一种数据类型,当用数组来记录学生的记录时,需多个不同类型的数组,操作不方便。C语言采用结构体类型来进行记录的描述。
一、结构体类型概述1、结构体概念及定义 结构体类型:由一些不同类型的数据组合而成的数据类型。如如:学生一般情况数据构成由:姓名、年龄、性别、民族、住址、电话等。2、定义如: struct student { char name[20]; int age; char sex; char nation; char address[20]; long tel; };一般形式: struct 结构体名 { 成员项表 };
注:定义结构体类型,不是定义变量,只是说明类型的结构,类型说明不占内存。
Student 是一个具有六个成员的结构体数据类型。引用时所占字节总数为:48字节(各成员所占字节总和)。
二、结构体类型变量的定义和引用1、结构体类型变量的定义(1)、定义了结构类型后定义变量 如:struct student worker,students; 类型标识符结构体变量 一般形式: sturct 结构体类型名变量名表;如:struct std { char name[10] int num; float score; }; struct std students,var;(2)定义结构的同时定义变量一般形式: sturct 结构体类型名 { 成员列表} 变量名表;
定义结构的同时定义变量举例
如:
struct std { char name[10] int num; float score; } struct std students,var;
(3)、直接定义结构体类型变量如:struct { char name[10]; int age; char sex; } students,worker;(4)、嵌套定义 在结构体中利用已经定义过的结构体类型来定义成员。如:struct date { int month; int day; int year; };
struct person
{
char name[10];
struct date birthday;
char sex;
int age;
};
结构体类型的内存分配:struct date{ int month; int day; int year;};struct person{ char name[10]; struct date birthday; char sex; int age;};
name[10]
birthday
sex
age
month
day
year
name[10]
birthday
month
day
year
sex
age
2、变量的初始化struct date{ i