核心概念
char *names[N]:指標陣列,每個元素指向一個字串首址。
- 排序時僅交換指標,不移動字串內容,效率高。
完整範例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
int n;
printf("國家個數: ");
scanf("%d", &n);
getchar(); // 吸收換行
char **names = malloc(n * sizeof(char*));
char buf[256];
for (int i = 0; i < n; ++i) {
fgets(buf, sizeof(buf), stdin);
buf[strcspn(buf, "\n")] = '\0';
names[i] = strdup(buf);
}
qsort(names, n, sizeof(char*), cmp);
printf("排序後:\n");
for (int i = 0; i < n; ++i) {
puts(names[i]);
free(names[i]);
}
free(names);
return 0;
}
關鍵點
- 使用
malloc 動態配置指標陣列與字串記憶體。
qsort 比較函數接收 const void*,需雙重解參考轉為 char*。
- 釋放記憶體時先釋放每個字串,再釋放指標陣列。