linear&binary search
void *lsearch(void* key,void base,int n,int elemSize, int (*cmpfn)(void *,void *))
{
for(int i<0;i<n;i++)
{
void* elemAddr=(char*)base+i*elemSize;
//要显式指明指针类型
if(cmpfn(key,elemAddr)==0)//callback
return elemAddr;
}
return NULL;
}
int array[]={4,2,3,7,11,6};
int size=6;
int number=7;
int* found=lsearch(&member,array,6,sizeof(int),intCmp);
if(found==NULL){...}
else{...}
int intCmp(void* elem1,void* elem2)
{
int* ip1=elem1;
int* ip2=elem2;
return *ip1- *ip2;
}
有时候array是指针数组那么cmp要跳两次
char *notes={"Ab","F#","B","Gb","D"}
char *favoritenote="Eb"
char **found=
//两个*是为了让机器意识到要跳两次
lsearch(&favoriteNote,notes,5,sizeof(char *),StrCmp)
//void*不可解引用,void**可以
int StrCmp(void* ip1,void* ip2)
{
char* s1=*(char **)vp1;
/*
char *s1=(char *)vp1;
对应lsearch(favoriteNote,notes,5,sizeof(char *),StrCmp)
*/
char* s2=*(char **)vp2;
return strcmp(s1,s2);
}
函数与方法(成员函数)的不同在于方法有this指针
静态方法没有this指针
void *bsearch(void* key,void* base,int n,int elemsize,int (*cmp)(void *,void*))
stack
stack.h
typedef struct{
int* elems;
int logicallen;//当前元素个数
int alloclength;//最大容量
}stack;
void StackNew(stack* s);
void StackDespose(stack* s);
void StackPush(stack* s,int value);
int StackPop(stack* s);
stack s;
StackNew(&s);
for(int i=0;i<5;i++)
{
StackPush(&s,i);
}
SatckDispose(&s);
void StackNew(stack *s)
{
s->logicallen=0;
s->alloclen=4;
s->elems=malloc(4*sizeof(int));
assert(s->elems!=NULL);
}