[英]Qsort not sorting char * array
我有一个问题,那就是qsort有时会排序内容,有时却不会。 这是我的代码
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int compare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
int main (){
int ile = 0;
scanf("%d", &ile);
const char * slowa[ile];
for(int j = 0; j <= ile; j++){
char string[30];
gets(string);
char * toAdd = strdup(string);
slowa[j] = toAdd;
}
qsort (slowa, ile, sizeof (const char *), compare);
for (int i = 0; i <= ile; i++) {
printf ("%s\n",slowa[i]);
}
return 0;
}
它适用于示例{ccc,bbb,aaa},但不适用于示例{afdg,sspade,trekk,bbre,lol}
所述scanf
已经离开在输入缓冲器中,这是由该第一读换行符gets
。
这两个循环迭代一次,对数组进行索引超出其范围。 我想您这样做是为了获得正确数量的表观输入。
因此,请在第一个循环之前清除输入(可能需要读取一个虚拟字符串),然后更正循环控制。
还请注意, gets()
现在已过时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.