c - 如何实现 qsort() 来处理结构数组?

标签 c arrays struct structure qsort

我必须解决几个 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;

关于c - 如何实现 qsort() 来处理结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536676/

相关文章:

c - 这是找到校验和的正确方法吗?

c - 在 Windows 中,如何阻止 fprintf 将\r 与\n 一起打印到文件

c - 将 int 写入 char 数组

c - fseek 和 fscanf 同时使用会导致程序崩溃

java - Java中如何操作数组?

python - 在 numpy 数组的第三个维度中,将前三个值乘以第四个值

java - 为什么不能在 while 循环中将 array[n] 与 null 进行比较?

无法对结构数组进行排序

C 结构的 C++ 类包装器

c - C中的位域内存使用