考虑qsort的这段代码:
#include <stdio.h>
#include <stdlib.h>
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc(const void * a, const void * b)
{
return *(int*)a - *(int*)b;
}
int main()
{
int n;
printf("Before sorting the list is: \n");
for (n = 0; n < 5; n++)
{
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for (n = 0; n < 5; n++)
{
printf("%d ", values[n]);
}
return(0);
}
*(int*)a
具体是什么意思?它看起来像指针指针?为什么我不能这样做:
**a // dereferrencing twice would get the value, no?
或
*(int *a) // looks about the same. Also why do i need the int?
如果这个问题看起来显而易见,那么道歉,因为我现在已经看了好几个小时了,而且我仍然无法理解为什么'*'围绕着这个问题。
答案 0 :(得分:2)
void*
和const void*
代表未知类型的通用指针。 qsort
并不真正知道它的排序:回调比较函数cmpfunc
执行该任务。但是C是静态类型的,因此回调函数需要具有特定的原型。这是const void*
有用的地方。
当然,在您提供的cmpfunc
中,您知道要排序的对象的类型,因此您可以投射 const void*
你的类型。这就是(int*)
正在做的事情:它是演员。
从技术上讲,你应该转而使用const int*
:
return *(const int*)a - *(const int*)b;
弃掉const
可以给您带来麻烦。
答案 1 :(得分:1)
无法取消引用指向void
的指针。因此,在给定的情况下,必须在解除引用之前强制转换为int *
。
在*(int*)a
中,(int*)
投射a
指向int
,然后在括号外*
取消引用该地址的值。