在學習 C 語言數據結構時,順序線性表是最基礎也最常見的結構之一。許多初學者在編寫「初始化 → 輸入數據 → 遍歷輸出」這套流程時,容易在指針分配、循環條件、數組下標等細節上踩坑。以下結合一段典型錯誤代碼,逐步分析並給出修正方案。
struct student* L; 在 main 中只是聲明了一個野指針,隨後直接傳給 init、shuru、traverse,會導致非法內存訪問。必須先 malloc 配置一塊 struct student 大小的堆內存。while(id) 應為 while(i < L->d),否則會陷入死循環或讀取越界數據。int age[20] 與 int d(當前長度)、int size(容量)混在一起,語義不清。建議改為 int *data 動態分配,或直接用定長數組並單獨記錄長度。shuru 中不判斷 L->d 是否達到 MAX,極易造成緩衝區溢出。#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct {
int *data; // 動態數組
int length; // 當前元素個數
int capacity; // 最大容量
} SeqList;
// 初始化
void init(SeqList *L) {
L->data = (int *)malloc(MAX * sizeof(int));
if (!L->data) exit(EXIT_FAILURE);
L->length = 0;
L->capacity = MAX;
}
// 輸入數據(以 0 結束,0 不存入)
void input(SeqList *L) {
int x;
while (L->length < L->capacity) {
printf("請輸入整數(0 結束):");
scanf("%d", &x);
if (x == 0) break;
L->data[L->length++] = x;
}
}
// 遍歷輸出
void traverse(SeqList *L) {
for (int i = 0; i < L->length; ++i) {
printf("%d ", L->data[i]);
}
printf("\n");
}
// 釋放內存
void destroy(SeqList *L) {
free(L->data);
L->data = NULL;
L->length = L->capacity = 0;
}
int main() {
SeqList L;
init(&L);
input(&L);
traverse(&L);
destroy(&L);
return 0;
}
data 存數據,length 記長度,capacity 記容量,語義清晰。掌握以上要點,順序線性表的基本操作就能寫得又對又穩,為後續鏈表、樹、圖等進階結構打好基礎。