为何C标准库msort调用时,带参数的cmpfunc无需传实参?
关于msort中传递比较函数的疑问解答
问题描述
我在阅读C标准库中的mergeSort(即msort函数)时发现,其定义包含一个比较函数参数:void msort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))。但实际调用msort时,传入的cmpfunc函数虽带有(const void *, const void *)两个参数,却没有传递实参。查看以下代码片段,想了解这种情况为何可行?
#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]); } msort(values, 5, sizeof(int), cmpfunc); printf("\nAfter sorting the list is:\n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } return(0); }
解答
这是因为你传递给msort的不是函数调用的结果,而是函数本身的地址(函数指针):
- 在C语言里,函数名本身就代表该函数在内存中的地址,直接写
cmpfunc就等价于&cmpfunc,也就是把这个函数的指针传给msort的compar参数。 - msort内部会负责调用这个比较函数,在排序过程中,它会从待排序的数组里取出元素地址,作为实参传给你定义的
cmpfunc。你写的cmpfunc不用在调用msort时传实参,这些实参是由msort的内部逻辑自动传递的。 - 直白点说:你只需要告诉msort“用哪个函数来比大小”,至于什么时候比、拿哪些元素来比,都是msort自己处理,你不用在传函数的时候就指定具体要比较的元素。
内容的提问来源于stack exchange,提问作者Solruhama
相关产品推荐
相关产品推荐

