gpt4 book ai didi

c - 为什么 qsort 中的比较器必须这样?

转载 作者:行者123 更新时间:2023-12-04 05:16:37 26 4
gpt4 key购买 nike

根据 C 引用标准库中提供的 qsort 函数具有以下形式

void 
qsort ( void * base, size_t num, size_t size, int ( * compar ) ( const void *, const void * ) );

我的问题是为什么比较函数必须有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com