Qsort 不排序 char * 数组

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() 现已过时。