I have to solve several C problems and most of them involve having to use qsort() somewhere but no matter how much I take help from the net I can't get it to work. Take this code for example:
#include <stdio.h>
#include <string.h>
struct date
{
int day;
int month;
int year;
};struct date d[5]={
{12,12,2012},
{23,02,2014},
{31,01,2222},
{32,21,2011},
{12,01,1990}
};
int compare(const void * a, const void * b)
{
struct date *orderA = (date *)a;
struct date *orderB = (date *)b;
return ( orderA->year -orderB->year );
}
int main()
{
int i;
qsort(d,5,sizeof(date),compare);
for(i=0;i<5;i++)
printf("%d %d %d\n",d[i].day,d[i].month,d[i].year);
return 0;
}
I get errors that date is undeclared even though it is already. And I can't understand compare functions at all and have to copy them from the net. Help me please. My teacher at college is a total imbecile.
Minor issues with your code: you need to include stdlib.h
(for qsort()
) but you're not using string.h
in your example; you use date
as a struct and a type but don't define it that -- you can define it as both at the same time via typedef
; you can expand your comparision beyond years if you want.
A rework of your code addressing the above issues:
#include <stdio.h>
#include <stdlib.h>
typedef struct date {
int day;
int month;
int year;
} Date;
int compare(const void *a, const void *b) {
const Date *date_A = a;
const Date *date_B = b;
return date_A->year == date_B->year ?
date_A->month == date_B->month ?
date_A->day - date_B->day
: date_A->month - date_B->month
: date_A->year - date_B->year;
}
int main() {
Date dates[] = {
{12, 12, 2012},
{23, 02, 2014},
{31, 01, 2222},
{32, 21, 2011},
{12, 01, 1990}
};
size_t count = sizeof(dates) / sizeof(Date);
qsort(dates, count, sizeof(Date), compare);
for (int i = 0; i < count; i++) {
Date *date = &dates[i];
printf("%d %d %d\n", date->day, date->month, date->year);
}
return 0;
}