#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    Qsort to compare strings for alphabetical order - C language


    I'm using the qsort() that comes with the library to sort an array of structures of strings.

    It's essentially an array of strings but with a structure that is containing the array.

    For example:

    typedef struct node {
    char name[MAX_SIZE + 1];
    } Node;

    Then my array of nodes that contains the names would be:

    Node nodes_list[MAX_SIZE + 1];

    My question is, I want to sort nodes_list so when I print the following:

    for (i = 0; i < size; i++) {
    printf("%s\n", nodes_list[i].name);
    }

    it prints all the names in alphabetical order.

    I would like to do sort the list using qsort and my comparator function is this:

    int compare(const void *a, const void *b) {
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
    }

    when I run the function with qsort:

    qsort(nodes_list, size, sizeof(Node), compare);

    I get a segmentation fault (core dumped).

    I know I am getting a seg. fault with this snippet of code because without it, I can print the list of names fine. Not sorted of course.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    40
    Rep Power
    19
    Cast 'const void *' to a pointer of Node-element before assign it to 'const char **'.

    Code:
    int compare(const void *a, const void *b) {
        const char **ia = ((Node *)a)->name;
        const char **ib = ((Node *)b)->name;
        return strcmp(*ia, *ib);
    }
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    You're not sorting an array of char pointers, you're sorting an array of Nodes.

    So the cast in your compare functions is wrong.

    Try say
    const Node *ia = a;

    Then use
    ia->name
    in the strcmp
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo