数组元素查找的通用写法举例

来源:互联网 发布:csgo知乎 编辑:程序博客网 时间:2024/05/16 23:11
  • 在一个整形数组中查找元素
#include <stdio.h>#include <string.h>void *lSearch(void* key, void* base, int n, int elemSize);int main(){    int array[] = {4,3,5,7,9,8};    int elemNum = 6;    int key = 70;    void *result = lSearch(&key, array, elemNum, sizeof(int));    if (result != NULL) {        printf("Get the item !\n");    } else { printf("Not get yet !\n"); }    return 0;}/* The function for item compareation */int StrCmp(void *vp1, void *vp2){    char *s1 = *(char**)vp1;    char *s2 = *(char**)vp2;    return strcmp(s1, s2);}/* The input is an integer array    key:  待查找的关键字内存存储位置   base: 待查找集合的内存存储位置   base: 待查找集合中的元素个数   elemSize: 待查找集合中每个元素的大小字节数*/void *lSearch(void* key, void* base, int n, int elemSize){    int i;    for (i=0; i<n; i++)    {        void *elemAddr = (char*)base + i*elemSize;        if (memcmp(key, elemAddr, elemSize) == 0) {             return elemAddr;        }    }    return NULL;}


  • 在一个字符指针数组中查找某一个字符串是否存在
#include <stdio.h>#include <string.h>int StrCmp(void *vp1, void *vp2);void *StrSearch(void* key, void* base, int n, int elemSize, int (*cmp)(void*, void*));int main(){    char *strArr[] = {"Ab", "B#", "CS", "D", "EF"};    char *key = "Ab";    if (StrSearch(&key, strArr, 5, sizeof(char*), StrCmp))                   {      printf("Get the item !\n");} else { printf("Not get the item !\n"); }    return 0;}/* The function for item compareation */int StrCmp(void *vp1, void *vp2){    char *s1 = *(char**)vp1;    char *s2 = *(char**)vp2;    return strcmp(s1, s2);}/* The input is an array which contains char* type items */void *StrSearch(void* key, void* base, int n, int elemSize, int (*cmp)(void*, void*)){    int i;    for (i=0; i<n; i++)    {        void *elemAdrr = (char*)base + i*elemSize;        if (cmp(key, elemAdrr) == 0) {            return elemAdrr;        }    }    return NULL;}
0 0
原创粉丝点击