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.
sizeof(struct date), also#include <stdlib.h>struct date* orderA = (struct date*)a;in the compare function.typedef struct date date;dateafter definingstruct date, but in C you must addtypedef struct date date;to be able to use the unqualified type namedate.