为了账号安全,请及时绑定邮箱和手机立即绑定

bsearch()函数里的最后一个形参是指向函数的指针啊,直接传入CMP为什么没有用?

bsearch()函数里的最后一个形参是指向函数的指针啊,直接传入CMP为什么没有用?

C
犯罪嫌疑人X 2022-11-18 18:14:39
#include <stdio.h>#include <stdlib.h>int CMP(int *a,int *b){if(*a<*b)return -1;else if(*a>*b)return 1;elsereturn 0;}int main(void){int search[10]={1,3,6,7,10,11,13,19,28,56} ;int a=13,*p,i;/*对数组search 进行二分搜索13*/p=(int *)bsearch(&a, search,10, sizeof(int),(int(*)(const void *,const void *))CMP);printf("The elems of the array are\n");for(i=0;i<10;i++)printf("%d ",search[i]);/*显示元素13 在原数组中的位置*/if(p)printf("\nThe elem 13 is located at %d of the array\n",p-search+1);elseprintf("\nSearch is fail!!\n");getchar();}p=(int *)bsearch(&a, search,10, sizeof(int),(int(*)(const void *,const void *))CMP);在CMP函数前为什么还要加强制类型转换?
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

你试运行一下这个代码:


#include <stdio.h>#include <stdlib.h>/*_CRTIMP __checkReturn void * __cdecl bsearch(__in const void * _Key, __in_bcount(_NumOfElements * _SizeOfElements) const void * _Base,        __in size_t _NumOfElements, __in size_t _SizeOfElements,        __in int (__cdecl * _PtFuncCompare)(const void *, const void *));*/int CMP(int *a,int *b){    int tmp = 0;    if(*a<*b)        tmp = -1;    else if(*a>*b)        tmp = 1;    else        tmp = 0;    printf("tmp = %d\n", tmp);    return tmp;}int main(void){    int search[10]={1,3,6,7,10,11,13,19,28,56} ;    int a=3,*p,i;    /* 对数组search 进行二分搜索a */    p=(int *)bsearch(&a, search, 10, sizeof(int),(int(*)(const void *,constvoid *))CMP);    printf("The elems of the array are\n");    for(i=0;i<10;i++)        printf("%d ",search[i]);    /*显示元素a 在原数组中的位置*/    if(p)        printf("\nThe elem %d is located at %d of the array\n",a, p-search+1);    else        printf("\nSearch is fail!!\n");    getchar();}


tmp = -1tmp = 0The elems of the array are1 3 6 7 10 11 13 19 28 56The elem 3 is located at 2 of the array

我在注释里面给你贴出来了bsearch的函数原形阿,你能看得出来的,类型mismatch的话肯定编译都会失败的阿


查看完整回答
反对 回复 2022-11-22
  • 1 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信