key
Pointer to the object that serves as key for the search, type-casted as a void*.
base
Pointer to the first object of the array where the search is performed, type-casted as a void*.
num
Number of elements in the array pointed by base.
size
Size in bytes of each element in the array.
comparator
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * pkey, const void * pelem );
The function must accept two parameters: the first one pointing to the key object, and the second one to an
element of the array, both type-casted as void*. The function should cast the parameters back to some data
type and compare them.
The return value of this function should represent whether the value pointed by pkey is considered less than,
equal, or grater than the value pointed by pelem by returning, respectively, a negative value, zero or a positive
value.
For types that support regular comparison operators, a general comparator function may look like:
|
key指向所要查找的元素,base指向进行查找的数组,nmem为查找长度,一般为数组长度,size为每个元素所占的字节数,一般用sizeof(...)表示,comp指向比较子函数,它定义比较的规则。需要注意的是,数据必须是经过预先排序的,而排序的规则要和comp所指向比较子函数的规则相同。如果查找成功则返回数组中匹配元素的地址,反之则返回空。对于有多于一个的元素匹配成功的情况,bsearch()未定义返回哪一个。
例:
|
结果如下:
found |