<系统函数实现>memcmp

这是我实现的memcmp函数:

 1 #include <stdio.h>
 2 #include <string.h>
 3 /*
 4 *int memcmp (const void *s1,const void *s2,size_t n);
 5 *º¯Êý˵Ã÷
 6 *memcmp()ÓÃÀ´±È½Ïs1ºÍs2ËùÖ¸µÄÄÚ´æÇø¼äÇ°n¸ö×Ö·û¡£×Ö·û´®´óСµÄ±È½ÏÊÇÒÔASCIIÂë±íÉϵÄ˳ÐòÀ´¾ö¶¨£¬´Î˳ÐòÒàΪ×Ö·ûµÄÖµ¡£memcmp()Ê×ÏȽ«s1µÚÒ»¸ö×Ö·ûÖµ¼õÈ¥s2µÚÒ»¸ö×Ö·ûµÄÖµ£¬
 7 *Èô²îΪ0ÔòÔÙ¼ÌÐø±È½Ïϸö×Ö·û£¬Èô²îÖµ²»Îª0Ôò½«²îÖµ·µ»Ø¡£ÀýÈ磬×Ö·û´®"Ac"ºÍ"ba"±È½ÏÔò»á·µ»Ø×Ö·û'A'(65)ºÍ'b'(98)µÄ²îÖµ(£­33)¡£
 8 *·µ»ØÖµ
 9 Èô²ÎÊýs1ºÍs2ËùÖ¸µÄÄÚ´æÄÚÈݶ¼ÍêÈ«ÏàͬÔò·µ»Ø0Öµ¡£s1Èô´óÓÚs2Ôò·µ»Ø´óÓÚ0µÄÖµ¡£s1ÈôСÓÚs2Ôò·µ»ØСÓÚ0µÄÖµ¡£
10 *p is src, q is des, len is length of p
11 *error     =-1
12 *p>q     >0
13 *p<q     <0
14 *p==q    =0
15 */
16 int _memcmp(const void *p,const void *q,int len)
17 {
18     if(!p || !q)
19     {
20         return -1;
21     }
22 
23    // while((*(char *)p != '\0') && (*(char *)q != '\0') && (len > 0))
    while(len > 0)//this is strcmp , memcmp should't test \0
24 { 25 //printf("p %p:%d q %p:%d len %d\n",p,*(char *)p,q,*(char *)q,len); 26 if((*(char *)p - *(char *)q) != 0) 27 { 28 29 return (*(char *)p-*(char *)q); 30 } 31 p++; 32 q++; 33 len--; 34 } 35 36 if((len > 0 ) && (*(char *)p != '\0')) 37 { 38 return 1; 39 } 40 41 if((len > 0 ) && (*(char *)q != '\0')) 42 { 43 return -1; 44 } 45 46 return 0; 47 } 48 49 50 int main(int argc, char **argv) 51 { 52 char *p = "abcfgf"; 53 54 char *q = "abcfg"; 55 56 int val; 57 58 val = memcmp(p,q,6); 59 printf("sys val is %d\n",val); 60 61 val = _memcmp(p,q,6); 62 63 printf("my val is %d \n",val); 64 65 return 0; 66 }

 

posted on 2013-07-24 15:00  净坛使者  阅读(817)  评论(0编辑  收藏  举报

导航