#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
int compare(const void* a, const void* b) {
return strlen((char*)a) - strlen((char*)b);
}
int main() {
int i, n;
scanf("%d", &n);
char** strings = malloc(n*sizeof(char*));
for(i=0; i<n;i++) {
strings[i]=(char*)malloc(sizeof(char*));
scanf("%s", strings[i]);
}
qsort(strings, n, sizeof(char*), compare);
for(i=0; i<n;i++)
printf("%s\n", strings[i]);
for(i=0; i<n;i++)
free(strings[i]);
free(strings);
return 0;
}
因此,我试图这样做,但它返回一个unsorted数组,我不知道应该改变什么,任何人都知道如何做到这一点?按字符串长度动态分配的动态分配的字符串的Qsort
[更新from comment:]
我忘了提及,应该通过串的长度进行排序。
'字符串[我] =(的char *)malloc的(的sizeof(字符*));'应该是'字符串[我] = malloc(MaxLength);'左右。你的排序标准是什么? – mch
噢,我忘了提及,它应该按字符串的长度排序 – Nikola
除了由mch提到的'malloc'问题,您的比较函数是无效的。 – melpomene