#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_WORDS 100
#define STRLEN 20
/*cmp函数传递两个成员的地址来进行比较。
由于该数组包含 char * 类型的元素,因此这些成员的地址具有 char ** 类型。
而strcmp 函数需要一对 char * ,
因此每个 const void * 参数必须首先转换为 const char ** 的预期类型,
并解引用以获得 strcmp 的正确类型。
如果直接return strcmp(w1, w2)比较的是:
指向字符数组的指针的值,而不是指向字符串的指针的值,
实际比较的是指针地址,而不是字符串的内容,
需要用二级指针解引用才能得到真正的字符串*/
int cmp(const void* w1, const void* w2) {
return strcmp(*(const char**)w1, *(const char**)w2);
}
int main(void) {
char* words[MAX_WORDS] = { NULL };
int len = 0;
while (1) {
printf("Enter word: ");
words[len] = malloc(sizeof(char) * (STRLEN + 1)); //还有\0
if (!words[len]) {
printf("Error: malloc failed\n");
exit(1);
}
gets(words[len]);
if (!strlen(words[len])) break;
len++;
}
qsort(words, len, sizeof(char*), cmp);
printf("\nIn sorted order: ");
for (int i = 0; i < len; i++) {
printf("%s ", words[i]);
}
printf("\n");
for (int i = 0; i < len; i++) {
free(words[i]);
}
return 0;
}
【C语言】18_用qsort函数自定义cmp实现字符串排序
于 2024-05-11 08:50:25 首次发布