论坛首页 编程语言技术论坛

C语言的线性搜索

浏览 3380 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-07-14   最后修改:2012-07-16
C
解决了。
#include <stdio.h>
#include <string.h>
#define PF printf
int main() {
    int intcmp(void *ip1, void * ip2);
    void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *));
    int arr[] = {4, 6, 2, 3, 11, 22, 15};
    int n = sizeof(arr) / sizeof(int);
    int key = 11;
    int *found = lsearch(&key, &arr, n, sizeof(int), intcmp);
    PF("found=%p", found);
    return 1;
}
int intcmp(void *ip1, void * ip2) {
    int *p1 = ip1;
    int *p2 = ip2;
    return *p1 - *p2 == 0;
}
void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)) {
    int i;
    for(i = 0; i < n; i ++) {
        void *elemArr = (char *)base + i * elemSize;
        if(cmpfun(key, elemArr) == 0)
            return elemArr;
    }

    return NULL;
}



正确应为

#include <stdio.h>
#include <string.h>
//#define PF printf
int main() {
    int intcmp(void *ip1, void * ip2);
    void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *));
    int arr[] = {4, 6, 2, 3, 11, 22, 15};
    int n = sizeof(arr) / sizeof(int);
    int key = 11;
    int *found = lsearch(&key, &arr, n, sizeof(int), intcmp);
    printf("found=%p (%d)", found, *(int *) found);
    return 0;
}
int intcmp(void *ip1, void * ip2) {
    int *p1 = ip1, *p2 = ip2;
    return *p1 - *p2;
}
void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)) {
    int i;
    for(i = 0; i < n; i ++) {
        void *elemArr = (char *)base + i * elemSize;
        if(cmpfun(key, elemArr) == 0)
            return elemArr;
    }

    return NULL;
}


论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics