陣列要求所有元素型別相同,但現實資料往往異質:學生資料包含姓名(字串)、學號(整數)、性別(字元)、成績(浮點數)。結構體(struct)正是為此而生——將不同型別的變數聚合為單一邏輯單元。
struct Student {
char name[20];
int id;
char sex;
float score;
};
struct Student stu1, stu2; // 宣告兩個變數
struct Student {
char name[20];
int id;
char sex;
float score;
} stu1, stu2;
struct {
char name[20];
int id;
char sex;
float score;
} stu1, stu2; // 無標籤,無法在別處復用此型別
. 運算子
struct Student stu;
strcpy(stu.name, "Zhang San");
stu.id = 2024001;
stu.sex = 'M';
stu.score = 92.5;
printf("%s, %d, %c, %.1f\n", stu.name, stu.id, stu.sex, stu.score);
struct Student class[50]; // 50 位學生
for (int i = 0; i < 50; ++i) {
printf("輸入第 %d 位學生: ", i+1);
scanf("%s %d %c %f", class[i].name, &class[i].id, &class[i].sex, &class[i].score);
}
struct Date {
int year, month, day;
};
struct Student {
char name[20];
int id;
struct Date birthday; // 巢狀結構體
float score;
};
struct Student stu;
stu.birthday.year = 2000;
stu.birthday.month = 5;
stu.birthday.day = 15;
// 存取路徑:stu.birthday.year
struct Student stu = {"Li Si", 2024002, 'F', 88.0};
struct Student stu = {
.name = "Wang Wu",
.id = 2024003,
.score = 95.5,
.sex = 'M'
};
struct Demo {
char c; // 1 byte
// 3 bytes padding
int i; // 4 bytes
double d; // 8 bytes
}; // sizeof = 16 (對齊到 8)
#pragma pack(n) 控制對齊(非標準,影響可移植性)| 操作 | 範例 |
|---|---|
| 指標存取 | struct Student *p = &stu; p->id = 100; |
| 整體賦值 | struct Student a = b;(淺拷貝,指標成員共用記憶體) |
| 比較 | 無內建比較,需逐成員比較或 memcmp(注意填充位元組) |
| 函數參數 | 大型結構體傳指標 void func(const struct Student *s) |
| 函數返回 | 可直接返回結構體值(C99 保證),或返回指標(需管理生命週期) |
typedef struct {
char name[20];
int id;
char sex;
float score;
} Student; // 直接用 Student 當型別名
Student stu1, stu2;
結構體是 C 語言建立抽象資料型別的基石。掌握「定義標籤、宣告變數、. 存取成員、巢狀建模、指定初始化、對齊意識」六大核心技能,並配合 typedef 簡化代碼,即可輕鬆驅動從學生管理系統到嵌入式協定解析的各類實戰專案。