tags:

views:

75

answers:

2

Hi,

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

+1  A: 

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.

Didier Trosset
A: 

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.

Michael Burr