0

I've got a problem, which is, qsort sometimes sorts stuff, sometimes it doesn't. Here's my code

#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;
}

It works well with example { ccc,bbb,aaa } but does not work for the example { afdg ,sspade , trekk, bbre, lol}

2
  • 2
    You iterate once too many, should be j < ile; and i < ile; Commented Dec 5, 2016 at 10:18
  • Possible duplicate of stackoverflow.com/q/5370753/1212012 Commented Dec 5, 2016 at 10:19

1 Answer 1

2

The scanf has left a newline in the input buffer, which is read by the first gets.

The two loops iterate once too many, indexing the array beyond its bounds. I guess you did that to get the correct number of apparent inputs.

So clear the input before the first loop, perhaps with a dummy string read, and correct the loop control.

Also please note that gets() is now obsolete.

Sign up to request clarification or add additional context in comments.

2 Comments

i've add fflush(stdin) and corrected the loop control, works perfectly. Thanks
@Karol.T please note that fflush(stdin) is non-standard behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.