在C语言中,结构体(
struct
)是一种用户定义的数据类型,用于将不同类型的变量组合在一起。它允许我们定义复杂的数据类型,便于更直观地表示现实中的对象。 关键点:
定义一个结构体时需要使用关键字 struct
。以下是基本语法:
#include <stdio.h>
struct Student {
int id; // 学号
char name[50]; // 姓名
float score; // 成绩
};
struct Student student1 = {1, "Alice", 95.5};
通过点运算符(.
)访问成员:
printf("学号: %d\n", student1.id);
printf("姓名: %s\n", student1.name);
printf("成绩: %.2f\n", student1.score);
结构体在内存中的存储取决于其成员的排列顺序和对齐方式。以下代码用于分析内存布局:
#include <stdio.h>
struct Example {
char c;
int i;
double d;
};
int main() {
struct Example e;
printf("结构体大小: %zu 字节\n", sizeof(e));
return 0;
}
输出示例:
结构体大小: 16 字节
struct Address {
char city[50];
int zipCode;
};
struct Person {
char name[50];
struct Address address;
};
struct Student *ptr = &student1;
printf("姓名: %s\n", ptr->name); // 使用 -> 访问成员
结构体数组用于存储多个结构体变量:
struct Student students[3] = {
{1, "Alice", 90.0},
{2, "Bob", 85.5},
{3, "Charlie", 88.0}
};
for (int i = 0; i < 3; i++) {
printf("学号: %d, 姓名: %s, 成绩: %.2f\n", students[i].id, students[i].name, students[i].score);
}
按值传递会复制整个结构体,效率较低:
void printStudent(struct Student s) {
printf("学号: %d, 姓名: %s, 成绩: %.2f\n", s.id, s.name, s.score);
}
按指针传递更高效:
void printStudentPtr(const struct Student *s) {
printf("学号: %d, 姓名: %s, 成绩: %.2f\n", s->id, s->name, s->score);
}
C语言编译器会根据平台规定对结构体进行对齐优化,确保高效访问。
位域允许我们压缩存储多个布尔值或小整数:
struct BitField {
unsigned int a : 1;
unsigned int b : 3;
unsigned int c : 4;
};
结合 malloc
动态分配结构体内存:
#include <stdlib.h>
struct Student *student = (struct Student *)malloc(sizeof(struct Student));
student->id = 1;
strcpy(student->name, "Alice");
student->score = 95.0;
free(student);
设计一个管理学生信息的程序,支持添加、删除、查询操作。
struct Student {
int id;
char name[50];
float score;
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct Student {
int id;
char name[50];
float score;
};
struct Student students[MAX];
int count = 0;
void addStudent(int id, const char *name, float score) {
students[count].id = id;
strcpy(students[count].name, name);
students[count].score = score;
count++;
}
void printStudents() {
for (int i = 0; i < count; i++) {
printf("学号: %d, 姓名: %s, 成绩: %.2f\n", students[i].id, students[i].name, students[i].score);
}
}
int main() {
addStudent(1, "Alice", 90.5);
addStudent(2, "Bob", 85.0);
printStudents();
return 0;
}