struct student {
int num;
char name[20];
struct student *next;
} // ← 此處缺少分號
typedef struct student STU;
編譯器報錯:expected ';' before 'typedef' 或語法錯誤指向 typedef 行。
在結構體定義結尾的大括號後加分號:
struct student {
int num;
char name[20];
struct student *next;
}; // ✅ 必須有分號
typedef struct student STU;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
int num;
char name[20];
struct student *next;
};
typedef struct student STU;
STU *creat(STU *top); // 前向聲明
int main() {
STU *top = NULL;
top = creat(top); // 創建鏈表
// 遍歷輸出
STU *p = top;
while (p) {
printf("%d %s\n", p->num, p->name);
p = p->next;
}
// 釋放內存
while (top) {
STU *tmp = top;
top = top->next;
free(tmp);
}
return 0;
}
STU *creat(STU *top) {
STU *tail = NULL, *p = NULL;
int num; char name[20];
while (1) {
printf("輸入學號 姓名 (0 結束): ");
if (scanf("%d %19s", &num, name) != 2) break;
if (num == 0) break;
p = (STU *)malloc(sizeof(STU));
p->num = num;
strcpy(p->name, name);
p->next = NULL;
if (!top) top = tail = p;
else { tail->next = p; tail = p; }
}
return top;
}
| 錯誤類型 | 現象 | 修正 |
|---|---|---|
| 結構體定義缺分號 | 編譯報錯指向後續聲明 | } 後加 ; |
| malloc 未判空 | 內存不足時解引用 NULL 崩潰 | if(!p) { perror("malloc"); exit(1); } |
| scanf 緩衝區溢出 | %s 無長度限制 | %19s 或 fgets |
| 遍歷修改 head 指針 | 丟失鏈表頭,無法釋放/二次使用 | 用臨時指針 p = head 遍歷 |
| 釋放後未置 NULL | 懸空指針,二次 free 崩潰 | free(p); p = NULL; |