FX-结构体
1. 结构体的定义
结构体的定义使用 struct
关键字,语法如下:
struct 结构体名 {
数据类型 成员1;
数据类型 成员2;
// 更多成员...
};
示例
struct Student {
int id; // 学号
char name[20]; // 姓名
float score; // 成绩
};
2. 结构体变量的声明
定义结构体后,可以声明结构体变量。
方法1:先定义结构体,再声明变量
struct Student {
int id;
char name[20];
float score;
};
struct Student stu1, stu2; // 声明两个结构体变量
方法2:定义结构体的同时声明变量
struct Student {
int id;
char name[20];
float score;
} stu1, stu2; // 直接声明变量
方法3:使用 typedef
简化结构体类型名
typedef struct {
int id;
char name[20];
float score;
} Student;
Student stu1, stu2; // 直接使用 Student 声明变量
3. 结构体成员的访问
结构体成员通过点运算符 . 访问。
struct Student {
int id;
char name[20];
float score;
};
int main() {
struct Student stu1;
stu1.id = 101;
strcpy(stu1.name, "Alice");
stu1.score = 95.5;
printf("ID: %d, Name: %s, Score: %.2f\n", stu1.id, stu1.name, stu1.score);
return 0;
}
4. 结构体指针
结构体指针用于指向结构体变量,通过 -> 运算符访问成员。
struct Student {
int id;
char name[20];
float score;
};
int main() {
struct Student stu1 = {101, "Alice", 95.5};
struct Student *p = &stu1; // 定义结构体指针
printf("ID: %d, Name: %s, Score: %.2f\n", p->id, p->name, p->score);
return 0;
}
5. 结构体数组
结构体数组用于存储多个结构体变量。
struct Student {
int id;
char name[20];
float score;
};
int main() {
struct Student stu[3] = {
{101, "Alice", 95.5},
{102, "Bob", 88.0},
{103, "Charlie", 92.3}
};
for (int i = 0; i < 3; i++) {
printf("ID: %d, Name: %s, Score: %.2f\n", stu[i].id, stu[i].name, stu[i].score);
}
return 0;
}
6. 结构体嵌套
结构体可以嵌套其他结构体。
struct Date {
int year;
int month;
int day;
};
struct Student {
int id;
char name[20];
struct Date birthday; // 嵌套结构体
};
int main() {
struct Student stu1 = {101, "Alice", {2000, 10, 15}};
printf("Birthday: %d-%d-%d\n", stu1.birthday.year, stu1.birthday.month, stu1.birthday.day);
return 0;
}
7. 结构体作为函数参数
结构体可以作为函数参数传递,可以按值传递,也可以按指针传递。
按值传递
void printStudent(struct Student stu) {
printf("ID: %d, Name: %s, Score: %.2f\n", stu.id, stu.name, stu.score);
}
按指针传递
void printStudent(struct Student *p) {
printf("ID: %d, Name: %s, Score: %.2f\n", p->id, p->name, p->score);
}
8. 结构体的大小
结构体的大小由所有成员的大小决定,但可能会因为内存对齐而增加。
struct Example {
char a; // 1 字节
int b; // 4 字节
double c; // 8 字节
};
int main() {
printf("Size of struct Example: %lu\n", sizeof(struct Example)); // 可能输出 16(内存对齐)
return 0;
}
9. 结构体的初始化
结构体可以在声明时初始化。
struct Student {
int id;
char name[20];
float score;
};
int main() {
struct Student stu1 = {101, "Alice", 95.5}; // 初始化
return 0;
}
10. 结构体的常见用途
-
表示复杂的数据结构(如链表、树等)。
-
存储数据库记录。
-
封装多个相关的数据项。
练习题
-
定义一个结构体
Point
,包含x
和y
两个成员,表示二维坐标。编写函数计算两点之间的距离。 -
定义一个结构体
Book
,包含书名、作者和价格。编写程序输入 5 本书的信息并输出最贵的一本书。
通过复习结构体的定义、使用和常见操作,可以更好地掌握C语言中复杂数据类型的处理能力。