0

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);
}
1
  • 3
    Have you looked at man qsort? The documentation explains what you need to do, and gives an example of how to use it. Commented Mar 22, 2012 at 17:40

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if it is a char that i want to compare
strcmp for strings or you can just use > < or ==
3

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);

1 Comment

Dear can you please be more specific. how do i use the cmp method in my code and how i then use the Qsort. can you give me the example using the code i posted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.