void Swap(void* vp1,void* vp2,int size){ //use of void:1.函数返回值 2.void * 3.void 不是变量类型 不能声明变量如 void tmp; is wrong char buffer[size]; memcpy(buffer,vp1,size); memcpy(vp1,vp2,size); memcpy(vp2,buffer,size); } void* Isearch(void* key,void* base,int n,int elem_size){ for(int i=0;i<n;i++){ void *tmp = (char*)base + i*elem_size; if(memcmp(tmp,key,elem_size)==0)return tmp; } return NULL; } void lesson4(){ cout<<"lesson4"<<endl; cout<<"1.generic function/n2.use of void */nswap function/nuse of memcpy() and memcmp()"<<endl; //swap of 2 ints cout<<"swap of 2 ints"<<endl; int i1=6,i2=100; cout<<"i1="<<i1<<" i2="<<i2<<endl; Swap(&i1,&i2,sizeof(int)); cout<<"i1="<<i1<<" i2="<<i2<<endl; //swap of 2 doubles cout<<"swap of 2 doubles"<<endl; double d1=6.12,d2=100.13; cout<<"d1="<<d1<<" d2="<<d2<<endl; Swap(&d1,&d2,sizeof(double)); cout<<"d1="<<d1<<" d2="<<d2<<endl; //swap of 2 pointers cout<<"swap of 2 pointers"<<endl; char* h,*w; h = strdup("Fred"); w = strdup("Wilma"); cout<<"husband="<<h<<" wife="<<w<<endl; Swap(&h,&w,sizeof(char*));// this is right, it exchanges the addrs the two pointers hold cout<<"husband="<<h<<" wife="<<w<<endl; Swap(h,w,sizeof(char*)); // this is wrong, it exchanges the char contents the two pointers point to cout<<"husband="<<h<<" wife="<<w<<endl; //search int in array int isize=2; int iarray[isize]; int ikey = 1; iarray[0]=1; iarray[1]=100; int* ip=(int *)Isearch(&ikey,iarray,isize,sizeof(int)); if(ip!=NULL) cout<<*ip<<endl; else cout<<ikey<<" is not in array"<<endl; //search double in array int dsize=2; double darray[dsize]; double dkey =5.2 ; darray[0]=5.2; darray[1]=600.12; double* dp=(double *)Isearch(&dkey,darray,dsize,sizeof(double)); if(dp!=NULL) cout<<*dp<<endl; else cout<<dkey<<" is not in array"<<endl; }