我正在尝试对这个字符串列表进行排序:["a", "z", "b"]。所以答案应该是 ["a", "b", "z"]。但是,当我尝试使用 C 的 qsort() 时,没有任何 Action !我做错了什么?
MWE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sortcmpfunc (const void *a, const void *b)
{ return strcmp((const char*)a, (const char*)b); }
int main(){
const char** list = (const char**)malloc(50*sizeof(const char*));
for(int i = 0; i < 50; i++){
list[i] = (char*)malloc(50*sizeof(char));
}
list[0] ="a";
list[1] = "z";
list[2] = "b";
for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");
qsort(list, 3, sizeof(const char*), sortcmpfunc);
for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");
return 0;
}
使用 gcc test-qsort.c && ./a.out
输出:
a z b
a z b
最佳答案
简单
strcmp(*(char **) a, *(char **) b);
请注意,每个元素的指针都会传递给比较函数,因此您需要转换为正确的类型并取消引用。
请避免
for (int i=0; i<3; i++){ printf("%s\n", list[i]); }
而是写
for (int i = 0; i < 3; i++) {
printf("%s\n", list[i]);
}
太可怕了
还有用
gcc -Wall -Werror test-qsort.c && ./a.out
关于c - 为什么当我使用 qsort() 对字符串数组进行排序时 qsort() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39812717/