user1254916
user1254916

Reputation: 69

How to sort Struct using qsort in C programming

I have created an array of struct and i would like to sort them using qsort to sort dates chronologically to the string month or i should say char month[]. how can i make the following code display the struct according to a month. please advice. thanks

struct dates
{
    int index;
    int day;
    int year;
    char month[15];
};


int i=0;
int count = 0 ;
char test ='\0';
int total =0;

printf("Please enter the number of dates you need to display");
scanf("%d",&total);
struct dates *ip[total];

for(count =0; count< total; count++){
    ip[count] = (struct dates*)malloc(sizeof(struct dates));

    printf("\nEnter the name month.");
    scanf("%s", ip[count]->month);

    printf("\nEnter the Day.");
    scanf("%d",&ip[count]->day);

    printf("\nEnter the Year.");
    scanf("%d", &ip[count]->year);                      
}

for(i=0; i<total; i++){
    printf("%s %d %d\n\n",ip[i]->month,ip[i]->day,ip[i]->year);
}

Upvotes: 0

Views: 11695

Answers (2)

hroptatyr
hroptatyr

Reputation: 4829

There's an example in the man page of qsort

static int
cmp(const void *p1, const void *p2)
{
        int y1 = ((const struct dates*)p1)->year;
        int y2 = ((const struct dates*)p2)->year;

        if (y1 < y2)
            return -1;
        else if (y1 > y2)
            return 1;

        /* years must be equal, check months */
        ...
}

and then

qsort(dates, total, sizeof(*dates), cmp);

Upvotes: 3

Bram
Bram

Reputation: 765

you can define your own comparator to sort http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

So to sort integers you would use

int intcomp(void *a, void *b){
  int *_a = (int *)a;
  int *_b = (int *)b;

  if(*_a > *_b) return -1;
  if(*_a == *_b) return 0;
  return 1;
}

I think you can make your own comparator function from that.

Upvotes: 3

Related Questions