1
votes

I'm trying to sort a structure I've created via qSort however it seems to be be doing what I expect it to.

This is my compare function

int compare(const void *a, const void *b) {
    const INPUT *p1 = a;
    const INPUT *p2 = b;
    return ((p1->startTime) - (p2->startTime));
}

Where INPUT is my structure and startTime is an int within it.

I call qsort by this

qsort(*global,fileNumber,sizeof(global)/fileNumber,compare);

Where global is the variable name of INPUT, fileNumber is how many entries are within the global variable.

From the printf statements I've written it seems to do nothing.

I've initialized at the beginning of my code global like this

INPUT *global[4];

Any ideas on what I've done wrong?

Thanks

2
What're the definitions of fileNumber and global? Not sure, but it looks like global is a pointer, so sizeof(global) may not be what you are after, and you probably don't want to dereference it in the first parameter either. - torak
Do you mean *global in the qsort line? Or just global? What's the type of "global"? - The Archetypal Paul
Taking the difference like that as the return value of your comparison function is almost always wrong. It's vulnerable to numeric overflow errors. - R.. GitHub STOP HELPING ICE

2 Answers

2
votes

As you send *global to qsort, I can imagine that you defined global as:

INPUT **global;

Thus, when you give sizeof(global)/fileNumber as third argument to qsort, sizeof is probably 4 (or 8 on a 64 bits systems). Then this argument is propably zero.

Hence qsort does nothing on a zero element array, and never calls compare.

1
votes

You global array is an array of pointers, not an array of INPUT structs. So your compare function should look something like:

int compare(const void *a, const void *b) {
    const INPUT **p1 = a;
    const INPUT **p2 = b;
    return (((*p1)->startTime) - ((*p2)->startTime));
}

And your call to qsort():

qsort(global,fileNumber,sizeof(global)/fileNumber,compare);

Of course, all this assumes that you are really using global as an array of pointers rather than a pointer to an array of INPUT structs.