「建立表格」在 C 語言中通常指動態資料結構,支援增刪改查 (CRUD),而非靜態二維陣列。鏈表 是最基礎、最靈活的選擇。
// 表格欄位定義 (範例:學生成績表)
typedef struct {
int id;
char name[32];
float score;
} RowData;
// 鏈表節點
typedef struct Node {
RowData data; // 數據域
struct Node *next; // 指標域
} Node;
// 表格管理結構 (封裝頭尾指標、行數、欄位資訊)
typedef struct {
Node *head;
Node *tail;
size_t row_count;
// 可擴展:欄位名稱陣列、欄位類型、排序索引等
} Table;
void table_init(Table *t) { t->head = t->tail = NULL; t->row_count = 0; }
void table_destroy(Table *t) {
Node *cur = t->head, *next;
while (cur) { next = cur->next; free(cur); cur = next; }
table_init(t);
}
bool table_append(Table *t, const RowData *data) {
Node *node = malloc(sizeof(Node));
if (!node) return false;
node->data = *data;
node->next = NULL;
if (!t->head) t->head = node;
else t->tail->next = node;
t->tail = node;
t->row_count++;
return true;
}
Node* table_find_by_id(Table *t, int id) {
for (Node *p = t->head; p; p = p->next)
if (p->data.id == id) return p;
return NULL;
}
bool table_delete_by_id(Table *t, int id) {
Node *prev = NULL, *cur = t->head;
while (cur) {
if (cur->data.id == id) {
if (prev) prev->next = cur->next;
else t->head = cur->next;
if (cur == t->tail) t->tail = prev;
free(cur);
t->row_count--;
return true;
}
prev = cur;
cur = cur->next;
}
return false;
}
void table_print(const Table *t) {
printf("%-5s %-20s %s\n", "ID", "Name", "Score");
printf("------------------------------\n");
for (Node *p = t->head; p; p = p->next)
printf("%-5d %-20s %.1f\n", p->data.id, p->data.name, p->data.score);
}
prev 指標,支援反向遍歷、O(1) 尾部刪除。realloc 擴容的動態陣列 (Vector) 緩存局部性更好,速度更快。int main() {
Table t; table_init(&t);
table_append(&t, &(RowData){1, "Alice", 85.5});
table_append(&t, &(RowData){2, "Bob", 92.0});
table_print(&t);
Node *found = table_find_by_id(&t, 1);
if (found) printf("找到: %s\n", found->data.name);
table_delete_by_id(&t, 1);
table_print(&t);
table_destroy(&t);
return 0;
}
C 語言無內建表格類型,但靈活運用 struct + 指標 + 動態記憶體,即可構建功能完整、高效能的表格系統。掌握鏈表增刪改查是 C 程式設計師的基本功,進階可封裝為通用容器庫。