11.1 概述
在c语言中有很多简单变量,但难以将他们相互建立联系,如下表
num | name | sex |
---|---|---|
10010 | lijin | M |
在程序中要用到表中的数据结构,但是C语言中没有现成的数据,我们就可以自己在程序中建立所需的结构体类型。
例如:
struct student
{int num;
char name;
char sex;
}
切勿忘记定义变量后的分号,以上就是程序猿指定的一个结构体的类型。struct是声明结构体的关键字不能省略。struct student是类型名,与系统定义的int char float是一个样。只是struct student是我们自己定义的。
声明一个结构体变量的一般形式为:
**struct 结构体名
{成员列表}**
上表中的num name sex是成员,然后对成员进行类型声明。
类型名 成员名。
11.2 定义结构体变量的方法
1.先声明结构体类型再定义变量
struct student student1, student2; 定义了student1 student2为struct student类型变量。
2.声明类型的同时定义变量
struct student
{int num;
char name;
char sex;
}student1,student2;
这种方法的一般形式:
struct 结构体名
{
成员表列
}变量名表列;
3.直接定义结构体变量
一般形式为:
strcut
{
成员表列
}变量名表列;
成员也可以是一个结构体变量
strcut date
{
int month;
int day;
int year;
};
strcut student
{
int num;
int name;
inr sex;
struct date birthday;
}student1, student2;