結構體是 C 語言構建複雜數據類型的基石。本文系統覆蓋:定義語法、變量聲明、指針操作、動態內存管理、單鏈表實現,附圖解與完整代碼。
// 1. 先定義類型,再聲明變量
struct Student {
int number;
char name[10];
float score;
};
struct Student st1, st2, st3;
// 2. 定義同時聲明
struct Student {
int number;
char name[10];
float score;
} st1, st2, st3;
// 3. 定義並初始化
struct Student st1 = {101, "wang", 87.5};
// 4. 結構體數組
struct Student stu[50] = {
{101, "wang", 87.5},
{102, "li", 90},
// ...
};
struct Student *p; // 聲明指針
struct Student st1 = {...};
p = &st1; // 指向結構體變量
// 成員訪問三種等價寫法
p->number; // 箭頭運算符(最常用)
(*p).number; // 解引用後點運算符
st1.number; // 直接訪問
struct Student stu[10] = {...};
struct Student *p = stu; // 指向首元素
for (; p < stu + 10; p++) // p++ 自動跨越 sizeof(Student) 字節
printf("%d %s\n", p->number, p->name);
| 函數 | 原型 | 特性 | 典型用法 |
|---|---|---|---|
malloc | void *malloc(size_t size) | 不初始化,速度快 | (Student*)malloc(sizeof(Student)) |
calloc | void *calloc(size_t n, size_t size) | 自動歸零,較慢 | (Student*)calloc(10, sizeof(Student)) |
realloc | void *realloc(void *ptr, size_t size) | 調整大小,可能移動 | 擴容數組:realloc(ptr, new_size) |
free | void free(void *ptr) | 釋放內存 | free(ptr); ptr=NULL; 防野指針 |
memset(ptr, 'm', 20); // 按字節填充 memcpy(dest, src, 6); // 內存拷貝(不關心類型) memcmp(ptr1, ptr2, 100); // 內存比較

// 節點定義
struct Node {
char *name;
struct Node *next;
};
// 創建鏈表(頭插法)
struct Node* create_list(int n) {
struct Node *head = malloc(sizeof(struct Node));
head->next = NULL;
struct Node *tail = head;
for (int i = 0; i < n; i++) {
struct Node *p = malloc(sizeof(struct Node));
printf("input name:\n");
scanf("%s", p->name);
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
// 遍歷打印
void print_list(struct Node *head) {
struct Node *p = head->next;
while (p) {
printf("%s -> ", p->name);
p = p->next;
}
printf("NULL\n");
}
// 銷毀鏈表
void destroy_list(struct Node *head) {
struct Node *p = head;
while (p) {
struct Node *next = p->next;
free(p);
p = next;
}
}
struct Student *p = malloc(sizeof(struct Student)); —— **sizeof 類型**,不是 sizeof(p)char *name 需單獨 malloc/strdup,別直接指向字面量free 後**必須置 NULL**,防止雙重釋放/使用已釋放內存struct { int len; char data[]; } 實現變長結構體結構體 + 指針 + 動態內存 = C 語言構建任意複雜數據結構的「鐵三角」。熟練掌握,數據結構與算法不再是紙上談兵。