#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