开发者

qsort not sorting structure correctly

开发者 https://www.devze.com 2023-01-22 02:07 出处:网络
I\'m trying to sort a structure I\'ve created via qSort however it seems to be be doing what I expect it to.

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->开发者_如何学CstartTime) - (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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号