user1864758
user1864758

Reputation: 35

2D Array: Alphabetical Sorting in C

char **items

This is how I create my array. items[0] is the first string, items[1] is the second etc.. I want to sort those strings alphabetically, so for example:

c.bmp (items[0])
b.bmp (items[1])
a.bmp (items[2])

becomes:

a.bmp (items[0])
b.bmp (items[1])
c.bmp (items[2])

But when I do qsort: (where i is the number of strings)

qsort(items, i, (sizeof(char *)), cmp);

It does not end up in order. The order changes, but it is not alphabetical.

Here is my cmp function:

int cmp(const void *a, const void *b) { 
    char** p1 = (char**) a;

    char** p2 = (char**) b;

    if( p1[1] > p2[1])
    {
        return -1;
    }
    else if (p1[1] < p2[1])
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

Upvotes: 1

Views: 646

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Your cmp function is not comparing the strings, only their places in memory (even worse - the places in memory of things after them, i.e. p1[1] instead of p1[0], which also produces undefined behavior when the last element of the array participates in comparison).

You can fix this by using strcmp inside your cmp after dereferencing the pointers passed into your code:

int cmp(const void *a, const void *b) {
    char** p1 = (char**) a;
    char** p2 = (char**) b;
    return strcmp(*p1, *p2);
}

Upvotes: 4

Related Questions