如何实现 qsort() 以用于结构数组?

How to implement qsort() to work for an array of structures?

我必须解决几个 C 问题,其中大部分涉及必须在某处使用 qsort(),但无论我从网上寻求多少帮助,我都无法让它工作。 以此代码为例:

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

}

我得到的错误是日期未声明,尽管它已经声明了。而且我根本无法理解比较功能,不得不从网上复制它们。请帮帮我。我的大学老师就是个白痴。

date 不是类型。 struct date 是。引用结构类型时需要使用 struct 关键字。

此外,如果您将比较函数中的指针定义为 const,则不需要强制转换。

const struct date *orderA = a;
const struct date *orderB = b;

您的代码存在一些小问题:您需要包含 stdlib.h(对于 qsort()),但您没有在示例中使用 string.h;您将 date 用作结构和类型,但不要将其定义为 - 您可以通过 typedef 同时将其定义为两者;如果你愿意,你可以把你的比较扩大到几年之后。

针对上述问题对您的代码进行返工:

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