C语言通用交换和查询函数
#include
#include
#include
using namespace std;
void swap(void *a,void *b,int size)
{
unsigned char t[size];
memcpy(t,a,size);
memcpy(a,b,size);
memcpy(b,t,size);
}
// n数组大小 m找的数据类型占多少个字节
// 通用查找方法1
void* search1(void* a,void* k,int n,int m)
{
for(int i = 0; i < n; i++)
{
void* loc = (char*)a + i * m;
if(memcmp(loc,k,m) == 0)
return loc;
}
return NULL;
}
// 通用查找方法2(字符串查找
void* search2(void* a,void* k,int n,int m,int (*cmp1)(void* ,void*))
{
for(int i = 0;i < n; i++)
{
void* addr = (char*)a + i*m;
if(cmp1(addr,k) == 0)
{
return addr;
}
}
return NULL;
}
// 字符串比较
int cmp1(void* x,void* y)
{
char* a= *(char**)x;
char* b= *(char**)y;
return strcmp(a,b);
}
int main()
{
int x = 10;
int y = 20;
int arr[5] = {0,1,2,3,4};
int lenArr = 5;
int k = 2;
swap(&x,&y,sizeof(int));
printf("x = %d, y = %d\n",x,y);
int result = *(int *)search1(arr,&k,lenArr,sizeof(int));
printf("在int数组中查找到的元素: result = %d\n",result);
if(result != 0)
{
printf("存在该元素!\n");
}else{
printf("不存在该元素!\n");
}
char* books[] = {"book1","book2","book3","book4"};
int lenBooks = 4;
char* book = {"book2"};
char* test = {"book2"};
int result1 = cmp1(&book,&test);
printf("测试cmp1方法的返回值是否为0: %d\n",result1);
char* result2 = *(char **)search2(books,&book,lenBooks,sizeof(char*),cmp1);
printf("在字符串数组中查找到的元素:result2 = %s\n",result2);
if(strcmp(book,result2))
{
printf("存在该元素!\n");
}else{
printf("不存在该元素!\n");
}
}