一、概念
1. 结构体是由基本数据类型构成的,并由一个标识符来命名的各种变量的组合。结构体中可以使用不同的数据类型。
2. 在实际应用中,我们通常需要由不同类型的数据来构成一个整体,比如学生这个整体可以由姓名、年龄、身高等数据构成,这些数据都具有不同的类型,姓名可以是字符串类型,年龄可以是整型,身高可以是浮点型。
二、结构体的定义
1. 定义形式
结构体内部的元素,也就是组成部分,我们一般称作“成员”
结构体定义形式一般是:
struct 结构体名{
类型名1 成员名1;
类型名2 成员名2;
……
类型名n 成员名n;
};
如我们定义一个Person
struct Person {
char *name;
int age;
char *sex;
};
2. 定义结构体变量
前面只是定义了名字为Student的结构体类型,并非定义了一个结构体变量,就像int一样,只是一种类型。
结构体定义有多种样式:
1> 先定义结构体类型,在定义变量
struct Student {
char *name;
int age;
};
struct Student stu;
2> 定义结构体的同时定义变量
struct Student {
char *name;
int age;
} stu;
3> 直接定义结构体类型变量,省略类型名
struct {
char *name;
int age;
}stu;
三、注意事项
1. 不允许对结构体本身递归定义
struct Student {
int age;
struct Student stu; // 这里定义是错误的
};
2. 结构体内可以包含别的结构体
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
3. 定义结构体类型,只是说明了该类型的组成情况,
并没有给它分配存储空间,就像系统不为int类型本身分配空间一样。只有当定义属于结构体类型的变量时,系统才会分配存储空间给该变量
struct Student {
char *name;
int age;
};
struct Student stu; // 这里才分配存储空间
4. 结构体变量占用的内存空间是其成员所占内存之和,而且各成员在内存中按定义的顺序依次排列
struct Student {
char *name; // 姓名
int age; // 年龄
float height; // 身高
};
四、结构体的初始化
将各成员的初值,按顺序地放在一对大括号{}中,并用逗号分隔,一一对应赋值。
比如初始化Student结构体变量stu
struct Student {
char *name;
int age;
};
struct Student stu = {"aa", 27};
只能在定义变量的同时进行初始化赋值,初始化赋值和变量的定义不能分开,下面的做法是错误的:
struct Student stu;
stu = {"aa", 27};
五、结构体的使用
1. 一般对结构体变量的操作是以成员为单位进行的,引用的一般形式为:结构体变量名.成员名
struct Student {
char *name;
int age;
};
struct Student stu;
// 访问stu的age成员
stu.age = 27;
2. 如果某个成员也是结构体变量,
可以连续使用成员运算符"."访问最低一级成员
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;
六、结构体数组
1. 定义形式与结构体变量一样,也有三种形式
struct Student {
char *name;
int age;
};
struct Student stu[5]; //定义1
2. 初始化
struct {
char *name;
int age;
} stu[2] = { {"MJ", 27}, {"JJ", 30} };
七、结构体作为函数参数
将结构体变量作为函数参数进行传递时,其实传递的是全部成员的值,也就是将实参中成员的值一一赋值给对应的形参成员。因此,形参的改变不会影响到实参。
#include <stdio.h>
// 定义一个结构体
struct Student {
int age;
};
void test(struct Student stu) {
printf("修改前的形参:%d \n", stu.age);
// 修改实参中的age
stu.age = 10;
printf("修改后的形参:%d \n", stu.age);
}
int main(int argc, const char * argv[]) {
struct Student stu = {30};
printf("修改前的实参:%d \n", stu.age); // 30
// 调用test函数
test(stu); // 30 10
printf("修改后的实参:%d \n", stu.age); // 30
return 0;
}
八、指向结构体的指针* 每个结构体变量都有自己的存储空间和地址,因此指针也可以指向结构体变量* 结构体指针变量的定义形式:
struct 结构体名称 *指针变量名* 有了指向结构体的指针,那么就有
3种访问结构体成员的方式 (等效)
结构体变量名.成员名
(*指针变量名).成员名
指针变量名->成员名
#include <stdio.h>
int main(int argc, const char * argv[]) {
// 定义一个结构体类型
struct Student {
char *name;
int age;
};
// 定义一个结构体变量
struct Student stu = {"MJ", 27};
// 定义一个指向结构体的指针变量
struct Student *p;
// 指向结构体变量stu
p = &stu;
/*
这时候可以用3种方式访问结构体的成员
*/
// 方式1:结构体变量名.成员名
printf("name=%s, age = %d \n", stu.name, stu.age);
// 方式2:(*指针变量名).成员名
printf("name=%s, age = %d \n", (*p).name, (*p).age);
// 方式3:指针变量名->成员名
printf("name=%s, age = %d \n", p->name, p->age);
return 0;
}