c - 不传递参数比较函数如何工作

标签 c sorting comparison quicksort qsort

我想对 struct 数组进行排序,但在理解比较函数的逻辑的同时,我感到困惑的是,比较函数在不调用 qsort() 函数时是如何工作的传递参数

在 Windows 上的代码块上使用 GCC:

代码

int compare(const void * a, const void * b);

struct cricketers
{
  int avrun;
  char name[30];
  int age;
  int notm;
}india[Max] = {
  122, "Sachin Tendulkar", 30, 67,
  97, "Virendra Sehwag", 35, 56,
  66, "Irfan Pathan", 32, 45,
  153, "Yusuf Pathan", 36, 21,
  101, "Yuvaraj Singh", 32, 45,
};

int main()
{
  int i;
  qsort(india, 5, sizeof(struct cricketers), compare);

  for (i = 0; i < 5; i++)
  {
    printf("Name : %s", india[i].name);
    printf("\nAge : %d", india[i].age);
    printf("\nTotal Test Matches played : %d", india[i].notm);
    printf("\nAverage Run : %d\n\n\n", india[i].avrun);
  }
  _getch();
  return 0;
}

int compare(const void * a, const void * b)
{
  return (*(int*)a - *(int*)b);
}

最佳答案

函数qsort在内部调用比较函数,并向其传递指向数组的两个元素的空指针。

根据 C 标准(6.7.2.1 结构和 union 说明符),结构的第一个成员的地址等于结构类型的整个对象的地址。

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

因此,将参数 a 的值转换为 int * 类型会产生该类型的数据成员 int avrun 的地址。结构。

尽管如此,此表达式 (*(int*)a - *(int*)b) 可能会由于有符号整数溢出而调用未定义的行为。

我将按以下方式编写比较函数。

int compare( const void *a, const void *b )
{
    const struct cricketers *left  = ( const struct cricketers * )a;
    const struct cricketers *right = ( const struct cricketers * )b;

    return ( right->avrun < left->avrun ) - ( left->avrun < right->avrun ); 
}

关于c - 不传递参数比较函数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903906/

相关文章:

sorting - 当没有可用的范围键时,Dynamodb 如何对查询结果进行排序?

python - 哪个键/值存储最有前途/最稳定?

Java:测试两个对象之间多个属性的不等式

c++ - 比较 C++ 中的结构

c++ - 无法通过 epoll-client 发送数据

c - 函数指针和函数由于参数不兼容

c - 调整数组中的位置以保持递增顺序

mysql - Laravel 按日期排序,空日期总是在最后

c - 从数字字符串中获取位

c 程序允许用户更改已经设置的 4 位引脚