如何在C编程中使用qsort对结构进行排序

如何在C编程中使用qsort对结构进行排序,c,C,我已经创建了一个struct数组,我想使用qsort对它们进行排序,将日期按时间顺序排序到字符串month,或者说char month[]。如何使下面的代码按月份显示结构。请给我一些建议。谢谢 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

我已经创建了一个struct数组,我想使用qsort对它们进行排序,将日期按时间顺序排序到字符串month,或者说char month[]。如何使下面的代码按月份显示结构。请给我一些建议。谢谢

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);
}
struct日期
{
整数指数;
国际日;
国际年;
半个月[15];
};
int i=0;
整数计数=0;
字符测试='\0';
int-total=0;
printf(“请输入需要显示的日期数”);
scanf(“%d”,总计(&T);
结构日期*ip[总计];
对于(计数=0;计数<总计;计数++){
ip[count]=(结构日期*)malloc(sizeof(结构日期));
printf(“\n输入名称month.”);
扫描频率(“%s”,ip[计数]->月份);
printf(“\n输入日期”);
scanf(“%d”,&ip[count]->day);
printf(“\n输入年份”);
扫描频率(“%d”,&ip[计数]->年);
}
对于(i=0;imonth,ip[i]->天,ip[i]->年);
}

您可以定义自己的比较器进行排序

所以要对整数进行排序,可以使用

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

我认为您可以从中创建自己的比较器功能。

您可以定义自己的比较器进行排序

所以要对整数进行排序,可以使用

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

我认为您可以从中创建自己的比较器功能。

qsort
manpage中有一个示例

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 */
        ...
}

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 */
        ...
}

你看过《男人》杂志了吗?文档解释了您需要做什么,并给出了如何使用它的示例。您看过
manqsort
?文档解释了你需要做什么,并给出了一个如何使用它的例子。亲爱的,你能更具体一点吗。如何在代码中使用cmp方法,然后如何使用Qsort。你能给我举个例子,用我发的代码吗。如何在代码中使用cmp方法,然后如何使用Qsort。你能给我一个使用我发布的代码的例子吗?如果它是一个我想比较字符串的字符,或者你可以只使用><或==如果它是一个我想比较字符串的字符,或者你可以只使用><或==怎么办==