C-standard-library-c-function-bsearch
提供:Dev Guides
Cライブラリ関数-bsearch()
説明
Cライブラリ関数 void bsearch(const void key、const void base、size_t nitems、size_t size、int( compar)(const void 、const void ))*関数は *nitems オブジェクトの配列を検索します、 key が指すオブジェクトに一致するメンバーの場合、 base が指す最初のメンバー。 配列の各メンバーのサイズは size で指定されます。
配列の内容は、 compar が参照する比較関数に従って昇順でソートされている必要があります。
宣言
以下は、bsearch()関数の宣言です。
void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))
パラメーター
- key -これは、検索のキーとして機能するオブジェクトへのポインタであり、void *として型キャストされます。
- base -これは、検索が実行される配列の最初のオブジェクトへのポインタであり、void *として型キャストされます。
- nitems -これは、baseが指す配列内の要素の数です。
- サイズ-これは、配列内の各要素のバイト単位のサイズです。
- compare -これは2つの要素を比較する関数です。
戻り値
この関数は、検索キーに一致する配列内のエントリへのポインタを返します。 キーが見つからない場合は、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