在C语言中,结构体(struct
)是一种自定义的数据类型,可以将不同类型的数据组合在一起。结构体的使用可以让程序更清晰、易维护,特别适合表示复杂的数据,如学生信息、商品信息等。
在C语言中,使用 struct
关键字定义结构体,语法格式如下:
struct 结构体名 {
数据类型 成员名1;
数据类型 成员名2;
...
};
#include
#include
// 定义结构体
struct Student {
char name[50];
int age;
float score;
};
int main() {
// 声明结构体变量并初始化
struct Student s1;
// 赋值
strcpy(s1.name, "Alice");
s1.age = 20;
s1.score = 88.5;
// 打印结构体成员
printf("姓名: %s\n", s1.name);
printf("年龄: %d\n", s1.age);
printf("分数: %.2f\n", s1.score);
return 0;
}
✅ 要点说明
.
操作符访问结构体成员。strcpy()
函数用于赋值字符串,不能直接使用 =
赋值。C语言支持多种结构体初始化方式:
struct Student s1;
s1.age = 20;
s1.score = 95.0;
strcpy(s1.name, "Bob");
struct Student s2 = {"Tom", 21, 92.5};
struct Student s3 = {.name = "Jerry", .age = 22, .score = 89.0};
结构体数组可以存储一组结构体变量,便于批量管理数据。
#include
#include
struct Student {
char name[20];
int age;
float score;
};
int main() {
struct Student students[3] = {
{"Alice", 20, 90.5},
{"Bob", 21, 85.0},
{"Charlie", 19, 88.0}
};
// 遍历结构体数组
for (int i = 0; i < 3; i++) {
printf("学生%d: 姓名=%s, 年龄=%d, 分数=%.2f\n",
i + 1, students[i].name, students[i].age, students[i].score);
}
return 0;
}
✅ 要点说明
students[i].name
:访问结构体数组中的成员。结构体指针可以指向结构体变量,实现动态内存分配和参数传递。
#include
#include
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student s = {"David", 22, 91.5};
struct Student *p = &s; // 指针指向结构体变量
// 使用 -> 运算符访问结构体成员
printf("姓名: %s\n", p->name);
printf("年龄: %d\n", p->age);
printf("分数: %.2f\n", p->score);
return 0;
}
✅ 要点说明
->
运算符访问结构体指针的成员。.
操作符不同,->
是结构体指针专用操作符。C语言中的结构体在内存中按内存对齐规则存储。内存对齐可以提高程序性能,但可能会导致字节填充,造成内存浪费。
#include
struct A {
char a; // 1字节
int b; // 4字节
short c; // 2字节
};
int main() {
printf("结构体A的大小: %lu 字节\n", sizeof(struct A));
return 0;
}
在大多数编译器上:
char
占 1 字节int
占 4 字节short
占 2 字节由于内存对齐,结构体的大小通常会比成员变量之和更大。编译器会自动对齐,以提升内存访问效率。
✅ 内存对齐规则
char
按 1 字节对齐int
按 4 字节对齐short
按 2 字节对齐结构体常用于将数据打包保存到文件或从文件读取。
#include
#include
#include
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student s = {"Eve", 23, 87.5};
// 写入文件
FILE *file = fopen("student.dat", "wb");
if (file == NULL) {
perror("文件打开失败");
return EXIT_FAILURE;
}
fwrite(&s, sizeof(struct Student), 1, file);
fclose(file);
// 从文件读取
struct Student s2;
file = fopen("student.dat", "rb");
fread(&s2, sizeof(struct Student), 1, file);
fclose(file);
printf("读取学生信息:姓名=%s, 年龄=%d, 分数=%.2f\n",
s2.name, s2.age, s2.score);
return 0;
}
✅ 要点说明
fwrite()
:将结构体写入文件。fread()
:从文件读取结构体。wb
和 rb
模式以二进制方式读写。