谁能解释一下下面的代码的作用吗?我是编程新手,目前正在学习 C。
const void * a
返回 ( *(int*)a - *(int*)b );
qsort(值,6,sizeof(int),比较);
/* qsort example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
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;
}
输出
这给出:10,20,25,40,90,100
最佳答案
这个:
const void * a
表示传递给函数的参数是指向 void 类型的指针,其值为只读。
这一行:
( *(int*)a - *(int*)b );
取消引用传递的指针,将它们解释为指向 int
的指针,并计算这些值之间的差异。
还有这个:
qsort (values, 6, sizeof(int), compare);
是对标准库的qsort()
函数的调用,其中compare
是实际比较值的函数。
关于c - 请用squart解释一些示例代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075541/