根据 C 引用,标准库中提供的 qsort 函数具有以下形式
void
qsort ( void * base, size_t num, size_t size, int ( * compar ) ( const void *, const void * ) );
我的问题是为什么 compar 函数必须具有 const void *
形式的参数const void *
是什么意思?
另一个问题是函数是否采用 const void *
形式的参数,它能改变这个指针所指向的值吗?
示例:
static int double_a_number(const void * val){
*(int *)val = *(int *)val * 2;
return 0;
}
这真的会让变量 val 加倍吗?
感谢您的帮助!
最佳答案
why the compar function has to have arguments in the form
const void *
因为这是 C 语言中最通用的类型。请记住,qsort
可用于对任何类型的数组进行排序。
Another question is if a function takes an argument of the form
const void *
, can it change the value that is pointed by this pointer?
如果不抛弃const
就不行。这通常是一个坏主意(这肯定是意想不到的,并且还可能导致未定义的行为或崩溃)。这在比较器函数中当然没有任何意义!
关于c - 为什么qsort中的比较器必须是这样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14184892/