简体   繁体   中英

Sorting array of strings with qsort

This program takes an integer value which then determines the amount of strings that can be inputted, once the user has entered the amount of strings that they specified they may input another integer and then input those amount of strings. Once done the program sorts the strings based on their lengths in descending order. However the qsort doesn't work, it ends up outputting how the order of when the strings were originally entered.

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>


int sort(const void * a, const void * b){
    size_t fa = strlen((const char *)a);
    size_t fb = strlen((const char *)b);
    return (fa < fb) - (fa > fb);

}

int main(void){

char pointer[100];
int n;
scanf("%d", &n);
char** strings = malloc(n * sizeof(char*));

int i;
for (i = 0; i < n; i++){
    scanf("%s", pointer);
    strings[i] = malloc(sizeof(char) * (strlen(pointer) + 1));
    strcpy(strings[i], pointer);

}

int m;
scanf("%d", &m);
strings = realloc(strings, (n + m) * sizeof(char*));
for (i = n; i < m + n; i++){

    scanf("%s", pointer);
    strings[i] = malloc(sizeof(char) * (strlen(pointer) + 1));
    strcpy(strings[i], pointer);
}

int a;
int g;
int k = m + n;
qsort(strings , a, 100, sort);
for (g = 0; g < k; g++){
    printf("%s", strings[g]);

    printf("\n");


}
}

You're not calling qsort correctly at all.

The 2nd parameter is the number of elements in the "array" that you are sorting. You're currently passing it a which as others have pointed out isn't set to anything. Compiling your code with the "-Wall" option will show you those kinds of errors.

The 3rd parameter is the size of one of the elements in the "array", but you've confused this with the size of an unrelated variable pointer ? You could write it like sizeof(strings[0]) .

The finished call should look like qsort(strings,k,sizeof(strings[0]),sort); .

But that still won't work because your sort() function is being passed two pointers to elements in your "array" ( char ** ) and you're treating them as two elements of the "array" ( char * ). So you'd want something like

size_t fa = strlen(*(char **)a);

Well, this:

int a;
int g;
int k = m + n;
qsort(strings , a, 100, sort);

makes no sense at all, a has no value so this is undefined behavior.

Also sort() is broken, it should just be strcmp() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM