在stdlib.h
,有功能的qsort()的原型声明:像qsort这样的C函数如何使用不同的数据类型?
void qsort(void *ptr, size_t count, size_t size,
int (*comp)(const void *, const void *));
显然,这是一个泛型编程。 我不知道它是如何实现的,如何从void *类型获取元素?
在stdlib.h
,有功能的qsort()的原型声明:像qsort这样的C函数如何使用不同的数据类型?
void qsort(void *ptr, size_t count, size_t size,
int (*comp)(const void *, const void *));
显然,这是一个泛型编程。 我不知道它是如何实现的,如何从void *类型获取元素?
void *
指针根据size_t size
(在qsort
的第三个参数)
首先,我们强制转换的void*
到char*
,然后根据size
(因为焦炭需要1
字节,从而增加将规模做指针运算铸造内置的数据类型()
char *ptr = (char*)vp; //here vp is void *p
*(ptr + (n-1)*size); //will give you nth element
:给予正确的指针运算)
编辑
例如
size =1 and want 3rd element it means it will give you 3rd char
size =4 and want 3rd element it means it will give you 3rd int or float
size =2 and want 3rd element it means it will give you 3rd short int
size =8 and want 3rd element it means it will give you 3rd double
注:大小是实现定义,因此可能会发生变化,以编译器
是的,我想知道的是具体的过程。例如,如何获得ptr中的第3个元素? –
@PyLion:看我的编辑 – Omkant
最后一个参数是一个函数指针。正如你隐式提到的,你必须在某个地方实现了这个功能。但是,当你实现它时,你确实知道指针的哪个指针实际上是你的void *元素。
在你的补偿功能,你要投你的2个参数为您要使用的指针类型,如下:
int myCompFn(const void * e1, const void * e2)
{
MyType *elem1=(MyType*)e1;
MyType *elem2=(MyType*)e2;
... /* then compare elem1 and elem2 regarding to there definition */
}
#include <stdio.h>
void compare_first_to_rest(void *ptr, size_t nelem,
size_t size, int (*cmp)(const void*, const void*)) {
unsigned i;
for(i = 1; i < nelem; ++i)
{
int res = cmp(ptr, (char*)ptr + i * size);
if(res < 0)
printf("First element is less than element at %u\n", i);
else if(res > 0)
printf("First element is greater than element at %u\n", i);
else
printf("First element is equal to element at %u\n", i);
}
}
int icmp(const void *x, const void *y) {
return *(int*)x - *(int*)y;
}
int main()
{
int x[] = { 5, 3, 6, 2, 4, 8, -1, 10 };
compare_first_to_rest(x, 8, sizeof(int), icmp);
}
正如你所看到的,`compare_first_to_rest”不了解它在第一个参数中收到的元素的类型。但是知道每一个的大小,就可以得到一个指向它们每一个的指针,并让函数指针完成这项工作。
对大多数答案的注意:这个问题是关于如何使用qsort()的** not **,它关于如何使用qsort内部qsort可以找出元素的位置void * – nos