現實實體常包含異構數據:學生有姓名、學號、性別、成績。數組要求元素同類型,無法直接建模。結構體(struct)將不同類型、固定數量、有序的成員聚合為單一類型,相當於其他語言的 record/class(無方法)。
struct Tag {
type1 member1;
type2 member2;
// ...
};
Tag:結構體標籤(可省略,匿名結構體)。
struct Student {
int num; // 學號
char name[20]; // 姓名
char sex; // 性別
float score; // 成績
};
// 1. 先定義後聲明
struct Student { ... };
struct Student stu1, stu2;
// 2. 定義同時聲明
struct Student { ... } stu1, stu2;
// 3. 匿名結構體直接聲明
struct { ... } stu1, stu2; // 無標籤,無法在別處復用類型
#define STU struct Student
STU stu1, stu2;
| 操作數 | 運算符 | 示例 |
|---|---|---|
| 結構體變量 | . | stu1.num = 101; |
| 結構體指針 | -> | pstu->num = 101; |
p->member 等價 (*p).member,-> 優先級高於 *,無需括號。stu.birthday.month。
struct Student a = {101, "Zhang", 'M', 85.5};
struct Student b;
b = a; // 逐成員拷貝,C 標準支持
.num=101, .name="Li"。
// 外部變量
struct Student stu1 = {101, "Zhang", 'M', 85.5};
struct Student stu2;
int main() { stu2 = stu1; ... }
// 靜態局部變量
void foo() {
static struct Student stu = {102, "Wang", 'F', 90.0};
...
}
struct Student class[5] = {
{101, "Li", 'M', 45.0},
{102, "Zhang",'M', 62.5},
{103, "He", 'F', 92.5},
{104, "Cheng",'F', 87.0},
{105, "Wang", 'M', 58.0}
};
// 訪問:class[i].score
float sum = 0; int fail = 0;
for (int i=0; i<5; ++i) {
sum += class[i].score;
if (class[i].score < 60) ++fail;
}
printf("平均: %.2f, 不及格: %d\n", sum/5, fail);
#define NUM 3
struct Contact { char name[20]; char phone[11]; };
int main() {
struct Contact list[NUM];
for (int i=0; i
注意:gets 不安全(無長度限制),現代代碼請用 fgets(buf, sizeof(buf), stdin) 並去除換行符。
.,指針用 ->。