Domanda

So I'm using qsort to sort an array of structs based on an int value within the struct I've called "key". But though my array is properly filled, it does not appear to be sorting my structs...

It would seem that qsort is never calling my comparison function. A simple test of a print out statement within the function shows this. My "test" never appears.

Comparison function:

int compare (const void *a, const void *b){
    struct Record* a_r = (struct Record*)(a);
    struct Record* b_r = (struct Record*)(b);

   /*test*/
     printf("test");

    return (a_r->key - b_r->key);
}

My qsort call:

    qsort(arr, (sizeof(arr)/sizeof(struct Record)), sizeof(struct Record), compare);

Is the problem with with my compare function? Or am I not passing in the right variables?

My array declaration:

struct Record *arr = malloc(size->st_size); //where st_size is stat() of input file
È stato utile?

Soluzione

sizeof(arr) is the size of the pointer, as arr is defined struct Record *. Divided by the size of one struct Record this is most probably 0.

Assuming your file contains only records, and you're reading the whole file, use size->st_size/sizeof(struct Record). Or even better, as you're probably going to need the number of records somewhere else anyway, set a variable after reading the input file and use that variable.

Altri suggerimenti

You need to pass size->st_size / sizeof(struct Record) rather than sizeof(arr) / sizeof(struct Record) because sizeof(arr) is the size of a pointer and, by inference, sizeof(Record) is equal to or larger than the size of a pointer (so you pass 0 or 1 elements to qsort(), so qsort() doesn't need to call the comparator because arrays of size 0 or 1 are already sorted.

Presumably, size->st_size is the size of a file of fixed length records, each of which is a struct Record. Otherwise, the malloc() doesn't make a lot of sense.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top