文档介绍:第10章结构体与共用体
自定义类型标识符
结构体的定义与引用
共用体的定义与引用
自定义类型标识符
一般格式:
typedef 原类型名新类型名
例如:
typedef int INTEGER;
typedef float REAL;
所以有:
int i;
float x;
INTEGER i ;
REAL x;
等价于
又如:
typedef int ARRAY[100];
ARRAY a, b, c;
int a[100],b[100],c[100];
等价与
定义一个新类型的步骤:
1、先按定义变量的方法写出定义语句;
如: int a[10];
2、将变量名用新类型名替换;
如: int ARRAY[10];
3、在最前面加typedef;
如: typedef int ARRAY[10];
4、然后可以用新类型名定义变量。
如: ARRAY a,b,c;
用typedef说明一种新类型名
数组可以表示一组类型相同的数据。
在实际中,通常需要通过一组不同类型的数据共同来描述某个实体。如:学生个人资料(学号、姓名、性别、年龄和学习成绩)。
C 语言提供的结构体就是这样一种数据类型,它由一组称为成员(域或元素)的数据成分组成,其中每个成员可以具有不同的类型,用来存放类型不同但又相互有关的数据。
结构体类型:是一种C语言没有定义、用户可以根据实际需要自己定义的构造型数据类型。
结构体的定义与引用
结构体数据类型说明的一般格式:
struct 结构体类型标识符
{
类型名1 结构成员名表1;
类型名2 结构成员名表2;
……
类型名n 结构成员名表n;
};
如:描述学生基本信息
struct student
{ int num;
char name[20];
char sex;
int age;
float score;
}
结构体类型的定义
如:表示日期
struct date
{ int month, day, year ;}
经上面定义之后:
struct student 和int , float 等标准类型标识符一样可用来定义变量、数组、指针变量等
结构体类型说明可以嵌套
如: 学生基本情况
struct student
{ int num;
char nume[20];
char sex;
int age;
struct date birthday;
float score;
}
struct student
{ int num;
char name[10];
char sex;
int age;
struct date
{ int year;
int month;
int day;
} birthday;
float score;
}
结构体类型的定义
结构体类型变量、数组和指针变量的定义
方法1: 先定义结构体类型,再定义结构体变量
如:
struct student
{ int num;
char nume[20];
char sex;
int age;
float score;
}
struct student std, *pstd, pers[3];
方法2:在定义结构体类型的
同时定义结构体变量
如:
struct student
{ int num;
char name[20];
char sex;
int age;
float score;
} std,*pstd, pers[3];
结构体类型变量、数组和指针变量的定义
方法4:使用typedef说明一个结构体类型名,然后用新类型名定义变量
如:
typedef struct student
{ int num;
char name[20];
char sex;
int age;
float score;
} STREC
STREC std,*pstd, pers[3];
方法3:直接定义结构体变量
如: struct
{ int num;
char nume[20];
char sex;
int age;
float score;
} std,*pstd, pers[3];
结构体类型变量、数组和指针变量的定义
typedef struct student
{ int num;
char name[20];
char sex;
int age;
float score;
} STREC
STREC std,*pst