qsort eines stringfeldes
-
Hallo,
nach sehr sehr langer Zeit wollte ich wieder mal etwas in C testen.
Ich find den Fehler hier leider nicht:#include <stdio.h> #include <stdlib.h> #include <string.h> int compar_str(const void *a, const void *b){ printf("vergleiche %s mit %s\n", (const char *) a, (const char *) b); return strcmp((const char *) a, (const char *) b); } int main(void){ char *str_array[5]; int i=0; for(i=0; i<5; i++){ str_array[i] = (char *) malloc(sizeof(char)*50); } strcpy(str_array[0], "Eins"); strcpy(str_array[1], "Zwei"); strcpy(str_array[2], "Drei"); strcpy(str_array[3], "Vier"); strcpy(str_array[4], "Fuenf"); strcpy(str_array[5], "Sechs"); for(i=0; i<5; i++){ printf("%s\n", str_array[i]); } qsort(&str_array, 5, sizeof(char *), compar_str); for(i=0; i<5; i++){ printf("%s\n", str_array[i]); } return 0; }
-
Wie wärs mit ner Fehlerbeschreibung?
-
Bashar schrieb:
Wie wärs mit ner Fehlerbeschreibung?
compar_str() gibt nur Muell aus.
Das Ergebnis ist nicht sortiert, aber veraendert:Fuenf Eins Zwei Drei Vier
-
Die Vergleichsfunktion erhält Zeiger auf die zu vergleichenden Objekte. Das es sich dabei bei dir um char-Zeiger handelt, sind die Argumente von compare_str folglich Zeiger auf Zeiger auf char:
int compar_str(const void *a, const void *b){ printf("vergleiche %s mit %s\n", *(const char **) a, *(const char **) b); return strcmp(*(const char **) a, *(const char **) b); }
Ach ja, und du solltest die Zuweisung an str_array[5] sein lassen.
-
Danke!