#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;/*對數(shù)組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 在原數(shù)組中的位置*/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函數(shù)前為什么還要加強制類型轉(zhuǎn)換?
1 回答

揚帆大魚
TA貢獻1799條經(jīng)驗 獲得超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; /* 對數(shù)組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 在原數(shù)組中的位置*/ 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的函數(shù)原形阿,你能看得出來的,類型mismatch的話肯定編譯都會失敗的阿
- 1 回答
- 0 關(guān)注
- 94 瀏覽
添加回答
舉報
0/150
提交
取消