kBisla kBisla - 8 days ago 9
C Question

Why this qsort() doesn't work?

Am sorting an array of strings (case insensitive).

qsort causes segmentation fault, probably my casting isn't proper.

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

int compare(const void *string1, const void *string2) {
char *a = (char*)(string1);
char *b = (char*)(string2);
printf("comparing %s AND %s\n", a, b);
return strcasecmp(a,b);
}

void sortListName(char **fileList, int noOfFiles) {
printf("Sorting\n");
qsort(fileList, noOfFiles, 260*sizeof(char), compare);
return;
}


**fileList = array of strings (filenames)

P.S. main() is obvious and works fine.

Answer

I would adjust things so that you're just sorting a simple array, in this case of pointers to char - qsort will arrange for you to get pointers to two elements in that array (that is, char ** pointers), and some basic dereferencing is needed to get you to the "pointers to char" comparable via strcasecmp. @Mark likely has sussed out the source of the 260 in your unseen calling code, but I'm not a big fan of those kinds of 2d arrays in C.

The following functions for me, with an example main() to exercise it.

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


int compare(const void *v1, const void *v2){
    char *a = *(char **)v1;
    char *b = *(char **)v2;

    printf("comparing %s to %s\n", a, b);

    return strcasecmp(a,b);
}


void sortListName(char **fileList, int noOfFiles){
    printf("Sorting\n");
    qsort(fileList, noOfFiles, sizeof(*fileList), compare); 
    return;

}

int
main(void)
{
    char *filenames[] = {
        "/var/www/icons/comp.gray.png",
        "/var/www/error/HTTP_SERVICE_UNAVAILABLE.html.var",
        "/var/www/icons/right.gif",
        "/var/www/error/HTTP_NOT_IMPLEMENTED.html.var",
        "/var/www/icons/pie3.png",
        "/var/www/icons/pie2.png",
        "/var/www/htdocs/manual/mod/mod_proxy_balancer.html",
        "/var/www/htdocs/manual/programs/rotatelogs.html",
        "/var/www/htdocs/manual/vhosts/mass.html",
        "/var/www/icons/movie.png",
        "/var/www/htdocs/manual/images/caching_fig1.png",
        "/var/www/htdocs/htdig/search.html",
        "/var/www/icons/generic.gif",
        "/var/www/htdocs/manual/mod/quickreference.html",
        "/var/www/icons/small/blank.png",
        "/var/www/icons/image2.gif"
    };

    int i, nf = (int) (sizeof(filenames) / sizeof(filenames[0]));

    puts("Unsorted:");

    for (i = 0; i < nf; i++) {
        puts(filenames[i]);
    }

    sortListName(filenames, nf);

    puts("Sorted:");

    for (i = 0; i < nf; i++) {
        puts(filenames[i]);
    }

    return 0;
}
Comments