Bar
Bar

Reputation: 194

C - qsort sends the wrong pointers to the comparator function?

My problem is that qsort seems to be sending weird pointers to the comparator function. The comparator function itself seems to be working fine if I create 2 gaps and send their pointers as arguements. However, when debugging I'm getting wrong values, even though the gap array is initialized correctly.

I am running the code on Windows 10 if that matters.

Gap definition and comparator function:

typedef struct open_space_t{
    ssize_t size;
    off_t start;
}Gap;

int GapComparator(const void * aa, const void * bb){
    ssize_t a = ((Gap*) aa)->size;
    ssize_t b = ((Gap*) bb)->size;

    if(a>b){
        return 1;
    }
    if(b>a){
        return -1;
    }
    else{
        return 0;
    }
}

Running qsort:

Gap** allGaps = malloc((2) * sizeof(*allGaps));
allGaps[0] = malloc(sizeof(*allGaps[0]));
allGaps[0]->size = 20;
allGaps[0]->start = 30044;
allGaps[1] = malloc(sizeof(*allGaps[0]));
allGaps[1]->size = 20;
allGaps[1]->start = 30064;
qsort(allGaps, 2, sizeof(*allGaps), GapComparator);

Upvotes: 0

Views: 197

Answers (1)

melpomene
melpomene

Reputation: 85767

The comparator receives pointers to the elements it should compare. Your array elements are pointers (Gap *). Therefore the comparator receives Gap **.

Fix:

int GapComparator(const void * aa, const void * bb){
    ssize_t a = (*(Gap**) aa)->size;
    ssize_t b = (*(Gap**) bb)->size;

Or alternatively:

int GapComparator(const void *aa, const void *bb) {
    const Gap **pa = aa, **pb = bb;
    ssize_t a = (*pa)->size;
    ssize_t b = (*pb)->size;

Upvotes: 5

Related Questions