---
title: "C语言的线性搜索"
author: "xlaohe1"
date: "2012-07-14T11:14:14Z"
tags: ["C"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2012-07-16T10:15:03Z"
id: 1592711
url: "https://namas.iteye.com/blog/1592711"
---

```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);
    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;
}


```