當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 bsearch()用法及代碼示例


描述

C庫函數void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))函數搜索一個數組nitems對象,其初始成員被指向base, 對於與指向的對象匹配的成員,通過key.數組每個成員的大小由size

數組的內容應根據引用的比較函數按升序排列compar

聲明

以下是 bsearch() 函數的聲明。

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))

參數

  • key- 這是指向用作搜索鍵的對象的指針,type-casted 作為 void*。

  • base - 這是指向執行搜索的數組的第一個對象的指針,type-casted 作為 void*。

  • nitems- 這是 base 指向的數組中的元素數。

  • size- 這是數組中每個元素的字節大小。

  • compare- 這是比較兩個元素的函數。

返回值

此函數返回指向數組中與搜索鍵匹配的條目的指針。如果未找到鍵,則返回 NULL 指針。

示例

下麵的例子展示了 bsearch() 函數的用法。

#include <stdio.h>
#include <stdlib.h>


int cmpfunc(const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int values[] = { 5, 20, 29, 32, 63 };

int main () {
   int *item;
   int key = 32;

   /* using bsearch() to find value 32 in the array */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) {
      printf("Found item = %d\n", *item);
   } else {
      printf("Item = %d could not be found\n", *item);
   }
   
   return(0);
}

讓我們編譯並運行上麵的程序,將產生以下結果 -

Found item = 32

相關用法


注:本文由純淨天空篩選整理自 C library function - bsearch()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。