版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://lovocas.blogbus.com/logs/190164253.html
liner search:
#include
#include
void * lsearch( void *key, void *base, int n, int elemSize, int (*compfunc)( void *, void *)) {
int i = 0;
for(i = 0; i < n; ++i) {
void * currentLoc = ( char *)base + i * elemSize;
if(!compfunc(currentLoc, key)) {
return currentLoc;
}
}
return NULL;
}
int intComp( void *a, void *b) {
return memcmp(a, b, sizeof( int));
}
void main() {
int arr[] = { 1, 2, 3, 4, 5};
int key = 2;
int * result = ( int *)lsearch(&key, arr, 5, sizeof( int), intComp);
if(result == NULL)
printf( "404 NOT FOUND");
else
printf( "FOUND IT: %d \n ", *result);
}
#include
void * lsearch( void *key, void *base, int n, int elemSize, int (*compfunc)( void *, void *)) {
int i = 0;
for(i = 0; i < n; ++i) {
void * currentLoc = ( char *)base + i * elemSize;
if(!compfunc(currentLoc, key)) {
return currentLoc;
}
}
return NULL;
}
int intComp( void *a, void *b) {
return memcmp(a, b, sizeof( int));
}
void main() {
int arr[] = { 1, 2, 3, 4, 5};
int key = 2;
int * result = ( int *)lsearch(&key, arr, 5, sizeof( int), intComp);
if(result == NULL)
printf( "404 NOT FOUND");
else
printf( "FOUND IT: %d \n ", *result);
}
注意点:
1.C中用 void * 实现泛型, void *指针类型不同于一般的职能类型,比如不能进行指针运算,因为不知道类型,当然这个类型的偏移量也不知道了。
2.intComp函数不能实现为 int intComp(int *, int *); 必须为void *。
3.void *的指针运算通常是先转换成一个byte的类型(char *),再进行运算。
4.注意string.h中memcpy memcmp strdup函数的用法。