Search code examples
csortingstructureqsort

How to sort an array** by a struct variable in C?


I have been recently up to a sorting structures in an array by a function qsort. I loaded an array** from .csv file. My structure looks like this.

typedef struct {
    int id;
    char regionName[25];
    char townName[25];
    int countOfMan;
    int countOfWoman;
} tTown;

I want to sort an array by amount of women in region. I have defined compare function and tried to sort it.

int compareWomenCount(const tTown* village1, const tTown* village2) {
    int result = 0;
    if (village1->countOfWoman < village2->countOfWoman) {
        result = -1;
    }
    else if (village1->countOfWoman > village2->countOfWoman) {
        result = 1;
    }
    return result;
}

This is my qsort:

void sortArray(tTown** region, int arrayLength) {
    qsort(region, arrayLength, sizeof(tTown*), compareWomenCount);
}

But it didn't work. Has anyone a clue, what to do?

Thank you!


Solution

  • The qsort function passes a pointer to each element of the array to the comparison function (basically it uses the address-of operator & on each element, as in &region[i]).

    If each element in the array is a pointer, what is passed is a pointer to a pointer.

    That means your comparison function will need to look like

    int compareWomenCount(const tTown** village1, const tTown** village2) {
        int result = 0;
        if ((*village1)->countOfWoman < (*village2)->countOfWoman) {
            result = -1;
        }
        else if ((*village1)->countOfWoman > (*village2)->countOfWoman) {
            result = 1;
        }
        return result;
    }
    

    Furthermore, the arguments of the sorting function needs to generic constant pointers (const void *) to be really correct, and then you should cast them to the correct pointer type inside the function.