Domanda

I'm trying to use qsort to sort a string of characters alphabetically. At the moment it just seems to be reversing the order of my string.

printf("unsorted %s\n", string);
qsort(string, strlen(string), sizeof(char), compare);
printf("sorted %s\n", string);

string is the string "ACBD". The second printf shows it as "DBCA". My comparison function is,

compare(const void *a1, const void *b1){
     const int *a2 = a1;
     const int *b2 = b1;

     if(*a2 == *b2){
         return 0;
     }
     else{
         if(*a2 < *b2){
             return -1;
         }
         else{
             return 1;
         }
    }
}

I'm sure I'm doing something pretty stupid but any help is appreciated.

Edit: string is declared as char string[1000]

È stato utile?

Soluzione

You want to do a character comparison but are actually doing an integer comparison (sizeof int > sizeof char).

Fix it as follows:

 char *a2 = a1;
 char *b2 = b1;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top