Reputation: 357
So I was tasked with grabbing a binary file, reading it into an array composed of structs then sorting it based on an array within the struct. The part that I'm stuck on is the sorting. I'm not sure if I'm supposed to sort it as an array (since the binary file is now an array) or sort it as a struct. Heres part of my code bellow.
typedef struct {
char FlightNumber[7];
char OriginCode [5];
char DestinationCode [5];
int Date [];
} FLIGHT;
int main(){
FLIGHT FlightData [3000];
/*opens file, freads it into the array then closes*/
/*trying to sort it based on OriginCode*/
int compare (const FLIGHT *a, const FLIGHT *b) {
FLIGHT *ia = (FLIGHT *)a;
FLIGHT *ib = (FLIGHT *)b;
return strcmp(ia->OriginCode, ib->OriginCode);}
qsort( FlightData, 3000, sizeof( FLIGHT ), compare);
/*to see if sorting worked...*/
for (i = 0; i < 100; i++){
printf ("%i) %s, %s, %s\n", i, FlightData[i].FlightNumber, FlightData[i].OriginCode, FlightData[i].DestinationCode );
}
}
Basically I'm lost on how to write the compare.
Upvotes: 1
Views: 6439
Reputation: 753900
First off, the comparator function should have the signature:
int compare(const void *v1, const void *v2);
Next, you convert the void pointers into your structure pointers:
const FLIGHT *ia = (FLIGHT *)v1;
const FLIGHT *ib = (FLIGHT *)v2;
Next, you need to compare things systematically, element by element:
int rc;
if ((rc = strcmp(ia->OriginCode, ib->OriginCode)) != 0)
return rc;
if ((rc = strcmp(ia->DestinationCode, ib->DestinationCode)) != 0)
return rc;
…
return 0; // Only if the two entries compare as identical
This sorts by origin airport code, destination airport code, then by other criteria you can decide (flight number, date). I note that you've not specified how the date is stored. Since it is an integer array (apparently a 'flexible array member'), you probably have 'year, month, day' separately in some sequence.
When you have a flexible array member, you should not define an array of the structure, because you cannot store anything in the flexible array member. You can have an array of pointers, but you need to allocate the structures separately. OTOH, you really don't need variable size arrays to describe a date. You should be using a fixed size array, or even a timestamp to give time and date. The residual problem is with flights that depart on one day and arrive on another — overnighters and flights across the international date line. You probably need a departure time and an arrival time, in practice.
See also (amongst many others, no doubt):
Upvotes: 1
Reputation: 141586
Note that Date
has zero-size here because you do not allocate any space for it. It would be undefined behaviour to dereference it.
The qsort comparison function has to have this type:
int compare(const void *a, const void *b)
Your comparator should work so long as you change your function signature to match this.
Upvotes: 2