1、结构体
a)当一个整体由多个数据构成时,我们可以使用数组来表示这个整体,但数组有个特点:内部的每一个元素都必须是相同类型的数据;
b)有时我们需要不用的数据类型来表示一个整体,比如学生这个整体可以由姓名(字符串)、年龄(整型),身高(浮点型)等数据构成,这时就可以用到结构体。它允许内部的元素是不同类型的数据;
c)结构体的定义(分号结尾):
struct 结构体名 {
类型名1 成员名1
类型名2 成员名2
......
类型名n 成员名3
};
d)定义一个结构体
// 定义一个名为Student的结构体,结尾必须要用分号
struct Student {
char *name; // 姓名
int age; // 年龄
float height; // 身高
};
void main() {
// 定义一个结构体变量,并赋值
struct Student stu = {"cobish", 22, 1.7f};
// 也可这样修改
stu.age = 22;
printf("name = %s\n", stu.name); // 输出:name = cobish
printf("age = %d\n", stu.age); // 输出:age = 22
printf("height = %.1 f\n", stu.height); // 输出:height = 1.7
}
e)定义一个结构体,可直接将变量名放结构体后面
void main() {
// 定义一个结构体变量
struct Student {
char *name;
int age;
float height;
} stu;
struct Student stu = {"cobish", 22, 1.7f};
}
f)当然可可以直接这样赋值
void main() {
// 也可直接定义并赋值
struct Student {
char *name;
int age;
float height;
} stu = {"cobish", 22, 1.7f};
}
g)当然结构体名字在这种情况下可以省略,但这样结构体不能重用
void main() {
// 当然结构体名字在这种情况下可省略,但这种结构体不能重用
struct {
char *name;
int age;
float height;
} stu = {"cobish", 22, 1.7f};
}
2、结构体注意点
a)不允许对结构体本身递归定义
struct Student {
int age;
struct Student stu; // 这是错误的
};
b)结构体内允许包含别的结构体
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
void main() {
struct Student stu = {"cobish", {2014, 10, 28}};
}
c)结构体跟数组一样,不允许先定义再赋值
struct Date {
int year;
int month;
int day;
};
void main() {
struct Date birth;
birth = {2014, 10, 28}; // 这是错误的
birth.year = 2014; // 这是正确的
}
3、结构体数组
a)定义结构体数组
struct Date {
int year;
int month;
int day;
};
void main() {
struct Date date[2] = {{1992, 1, 1}, {2014, 1, 1}};
printf("year = %d\n", date[0].year);
}
4、结构体作为函数参数
a)结构体传入的是形参,不改变原来结构体的数值
struct Student {
int age;
};
void test(struct Student stu) {
stu.age = 10;
}
void main() {
struct Student student = {29};
test(student);
printf("age = %d\n", student.age); // 输出:age = 29
}
5、指向结构体的指针
a)结构体指针变量的定义形式:struct 结构体名称 *指针变量名;
b)3中访问成员变量的方式
1. 结构体变量名.成员名
2. (*指针变量名).成员名
3. 指针变量名->成员名
c)结构体跟 int 一样是一种数据类型,所以结构体名字不像数组一样代表结构体的地址,需用&才能获取到它的地址;
struct Student {
int age;
};
void main() {
// 定义一个结构体变量
stuct Student student = {29};
// 定义一个结构体指针
struct Student *s;
// 让指针指向结构体
s = &student;
// 打印
printf("age = %d\n", student.age);
printf("age = %d\n", (*s).age);
printf("age = %d\n", s->age);
}