Search code examples
cstringsortingalphabetical

Comparing strings alphabetically in C


I'm writing the compare function that will get passed to a qsort, and I'm having trouble getting the string to sort alphabetically.

typedef struct{
    char title[30];
    //other irrelevant variables
} Album;

compare(Album * l, Album * r){

    if(l->title > r->title){
         return -1;
    }
    if(l->title == r->title){
        return 0;
    }
    else{
        return 1;
    }
}

qsort(albums, num_albums, sizeof(Album), compare);

I know this is probably wrong, but I'm not sure how to compare to char pointers alphabetically. Can someone help this old chap?


Solution

  • A bare array name evaluates to the address of the first array element. You need to compare the string contents, not the string addresses. There happens to be a nice function to do that—strcmp:

    compare(Album * l, Album * r) {
        return strcmp(l->title, r->title);
    }