您为什么不需要将参数传递给qsort比较器函数? [英] Why don't you need to pass arguments to a qsort comparator function?

查看:89
本文介绍了您为什么不需要将参数传递给qsort比较器函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码摘自此处.

* qsort example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 40, 10, 100, 90, 20, 25 };

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

int main ()
{
  int n;
  qsort (values, 6, sizeof(int), compare);
  for (n=0; n<6; n++)
     printf ("%d ",values[n]);
  return 0;
}

我们有一个带有签名的参数的compare函数,但是当我们在qsort中调用它时,不会传递任何参数. ab的值如何传递给函数?谢谢

We have a compare function with parameters in its signature but when we call it in qsort no arguments are passed. How are the values of a and b passed to the function? Thanks

推荐答案

在此表达式的上下文中:

In the context of this expression:

qsort (values, 6, sizeof(int), compare);

标识函数的子表达式compare衰减为指向该函数的指针(而不是函数调用).该代码实际上等效于:

the subexpression compare that identifies a function decays into a pointer to that function (and not a function call). The code is effectively equivalent to:

qsort (values, 6, sizeof(int), &compare);

当用作函数的参数时,这与数组发生的事情是完全相同的(您可能之前见过,但更经常被问到):

This is exactly the same thing that happens to arrays when used as arguments to a function (which you might or not have seen before but is more frequently asked):

void f( int * x );
int main() {
   int array[10];
   f( array );      // f( &array[0] )
}

这篇关于您为什么不需要将参数传递给qsort比较器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆