#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 *, const void *))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 = -1 tmp = 0 The elems of the array are 1 3 6 7 10 11 13 19 28 56 The elem 3 is located at 2 of the array |
我在注释里面给你贴出来了bsearch的函数原形阿,你能看得出来的,类型mismatch的话肯定编译都会失败的阿
- 1 回答
- 0 关注
- 83 浏览
添加回答
举报
0/150
提交
取消