当一个整体由多个数组构成时,我们可以用数组来表示这个整体,但是数组有个特点:内部的每一个元素都必须是相同类型的数据。
但是,在我们实际应用中,通常都需要用不同类型的数据来构成一个整体。比如学生这个整体,可以由姓名、年龄、身高等数据构成。姓名可以是字符串,年龄可以是整形,身高可以是浮点型。
为此,C语言专门提供了一种构造类型 —— 结构体,来解决上面的问题。它允许内部的元素是不同类型的。
结构体内部的元素,我们一般称为“成员”。
struct 结构体名{
类型名1 成员名1;
类型名2 成员名2;
……
类型名n 成员名n;
};
类型名1 成员名1;
类型名2 成员名2;
……
类型名n 成员名n;
};
struct是关键字,是结构体类型标志。
比如上面的,我们定义一个学生:
struct Student {
char *name; // 姓名
int age; // 年龄
float height; // 身高
} ;
定义结构体变量的方式有很多种。
先定义结构体类型,再定义变量:
struct Student {
char *name;
int age;
};
struct Student stu;
char *name;
int age;
};
struct Student stu;
定义结构体类型的同时定义变量:
struct Student {
char *name;
int age;
} stu;
char *name;
int age;
} stu;
我们也可以直接定义结构体类型变量,省略类型名:
struct {
char *name;
int age;
} stu;
而且,结构体的内部是可以包含别的结构体的:
char *name;
int age;
} stu;
而且,结构体的内部是可以包含别的结构体的:
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
有一点需要注意:定义结构体类型,只能说明了该类型的组成类型,并没有给他分配存储空间,就像系统不会给int类型本身分配存储空间一样,只有当定义属于结构体类型的变量时,系统才会分配存储空间给该变量。
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
有一点需要注意:定义结构体类型,只能说明了该类型的组成类型,并没有给他分配存储空间,就像系统不会给int类型本身分配存储空间一样,只有当定义属于结构体类型的变量时,系统才会分配存储空间给该变量。
结构体变量占用的内存空间是其成员所占内存之和,而且各成员在内存中按定义的顺序依次排列的。
如何初始化结构体呢?
struct Student {
char *name;
int age;
};
struct Student stu = {"MJ", 27};
char *name;
int age;
};
struct Student stu = {"MJ", 27};
这里需要注意的是:只能在定义变量的同时进行初始化赋值,初始化赋值和变量的定义不能分开:
//struct Student stu;
//stu = {"Jim", 27};
这样的做法是错误的。
结构体的使用:
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
struct Student stu;
stu.birthday.year = 1986;
stu.birthday.month = 9;
stu.birthday.day = 10;
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
struct Student stu;
stu.birthday.year = 1986;
stu.birthday.month = 9;
stu.birthday.day = 10;
一般我们可以连续使用运算符" . "来访问最低一级的变量。
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------