voidfunc1(){printf("func1 调用了\n");}voidfunc2(){printf("func2 调用了\n");}voidfunc3(){printf("func3 调用了\n");}//函数指针数组voidtest02(){void(*pArray[3])();
pArray[0]= func1;
pArray[1]= func2;
pArray[2]= func3;for(int i =0; i <3; i++){
pArray[i]();}}
提供一个打印函数,可以打印任意类型的数据
voidprintText(void* data,void(*myPrintInt)(void*)){myPrintInt(data);}voidmyPrintInt(void* data){int* num = data;printf("%d\n",*num);}voidtest01(){int a =10;printText(&a,myPrintInt);}
提供一个函数,实现可以打印任意类型的数组
voidprintAllArray(void* pArray,int eleSize,int len,void(*myPrint)(void*)){char* p = pArray;for(int i =0; i < len; i++){//获取数组中每个元素的首地址char* eleAddr = p + eleSize * i;//交换给用户做打印操作myPrint(eleAddr);}}voidmyPrintInt(void* data){int* num = data;printf("%d\n",*num);}voidtest01(){int arr[5]={1,2,3,4,5};int len =sizeof(arr)/sizeof(int);printAllArray(arr,sizeof(int),len,myPrintInt);}
数组查找
注意字符串比较
学习用地址取值
struct Person {char name[64];int age;};voidmyPrintperson(void* data){struct Person* p = data;printf("姓名:%s 年龄:%d \n", p->name, p->age);}//查找数组中的元素是否存在//参数1 数组首地址 参数2 每个元素的大小 参数3 数组元素个数 参数4 查找数据intfindArrayEle(void* pArray,int eleSize,int length,void*data,int(*myCompare)(void*,void*)){char* p = pArray;for(int i =0; i < length; i++){//每个元素的首地址char* eleAddr = p + eleSize * i;//if ( 数组中的变量的元素 == 用户传入的元素)if(myCompare(eleAddr,data)){return1;}}return0;}intmyComparePerson(void* data1,void* data2){struct Person* p1 = data1;struct Person* p2 = data2;/*if (strcmp(p1->name ,p2->name) == 0 && p1->age == p2->age)
{
return 1;
}
return 0;*/returnstrcmp(p1->name, p2->name)==0&& p1->age == p2->age;}voidtest02(){struct Person psersonArray[]={{"aaa",10},{"bbb",20},{"ccc",30},{"ddd",40},};int length =sizeof(psersonArray)/sizeof(struct Person);printAllArray(psersonArray,sizeof(struct Person), length, myPrintperson);//查找数组中指定的元素是否存在struct Person p ={"ccc",30};int ret =findArrayEle(psersonArray,sizeof(struct Person), length,&p, myComparePerson);if(ret){printf("找到了元素\n");}else{printf("未找到\n");}}