这是我实现的memcmp函数:
#include <stdio.h>
#include <string.h>
/*
*int memcmp (const void *s1,const void *s2,size_t n);
*º¯Êý˵Ã÷
*memcmp()ÓÃÀ´±È½Ïs1ºÍs2ËùÖ¸µÄÄÚ´æÇø¼äÇ°n¸ö×Ö·û¡£×Ö·û´®´óСµÄ±È½ÏÊÇÒÔASCIIÂë±íÉϵÄ˳ÐòÀ´¾ö¶¨£¬´Î˳ÐòÒàΪ×Ö·ûµÄÖµ¡£memcmp()Ê×ÏȽ«s1µÚÒ»¸ö×Ö·ûÖµ¼õÈ¥s2µÚÒ»¸ö×Ö·ûµÄÖµ£¬
*Èô²îΪ0ÔòÔÙ¼ÌÐø±È½Ïϸö×Ö·û£¬Èô²îÖµ²»Îª0Ôò½«²îÖµ·µ»Ø¡£ÀýÈ磬×Ö·û´®"Ac"ºÍ"ba"±È½ÏÔò»á·µ»Ø×Ö·û'A'(65)ºÍ'b'(98)µÄ²îÖµ(£33)¡£
*·µ»ØÖµ
Èô²ÎÊýs1ºÍs2ËùÖ¸µÄÄÚ´æÄÚÈݶ¼ÍêÈ«ÏàͬÔò·µ»Ø0Öµ¡£s1Èô´óÓÚs2Ôò·µ»Ø´óÓÚ0µÄÖµ¡£s1ÈôСÓÚs2Ôò·µ»ØСÓÚ0µÄÖµ¡£
*p is src, q is des, len is length of p
*error =-1
*p>q >0
*p<q <0
*p==q =0
*/
int _memcmp(const void *p,const void *q,int len)
{
if(!p || !q)
{
return -;
} // while((*(char *)p != '\0') && (*(char *)q != '\0') && (len > ))
while(len > 0)//this is strcmp , memcmp should't test \0
{
//printf("p %p:%d q %p:%d len %d\n",p,*(char *)p,q,*(char *)q,len);
if((*(char *)p - *(char *)q) != )
{ return (*(char *)p-*(char *)q);
}
p++;
q++;
len--;
} if((len > ) && (*(char *)p != '\0'))
{
return ;
} if((len > ) && (*(char *)q != '\0'))
{
return -;
} return ;
} int main(int argc, char **argv)
{
char *p = "abcfgf"; char *q = "abcfg"; int val; val = memcmp(p,q,);
printf("sys val is %d\n",val); val = _memcmp(p,q,); printf("my val is %d \n",val); return ;
}