memcmp和strcmp函数

本文详细解释了如何在C语言中使用memcmp和wmemcmp函数来比较两个缓冲区的字符,并对比了它们与strcmp函数的区别。重点说明了这些函数在字符串比较时的行为差异,特别是对于不同长度字符串的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Compare characters in two buffers.

int memcmp(    const void* buf1,    const void* buf2,    size_t count );

inline int wmemcmp (   const  wchar_t* buf1, const wchar_t* buf2, size_t count);

Parameters


       buf1    :  First buffer.
       buf2    :  Second buffer.
       count   : Number of characters.
       Return Values   : The return value indicates the relationship between the buffers.

       Return Value Relationship of First count Bytes of buf1 and buf2
        < 0         buf1 less than buf2
        = 0         buf1 identical to buf2
        > 0         buf1 greater than buf2

二、memcmp与strcmp的区别

int   memcmp(const   void   *   cs,const   void   *   ct,size_t   count)  
{  

     const   unsigned   char   *su1,   *su2;  
     int   res   =   0;  
   
for( su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
          if   ((res   =   *su1   -   *su2)   !=   0)  
          break;  
          return   res;  
}  
   
int   strncmp(const   char   *   cs,const   char   *   ct,size_t   count)  
{  
     register   signed   char   __res   =   0;      
     while   (count)  

     {  
          if   ((__res   =   *cs   -   *ct++)   !=   0   ||   !*cs++)  
          break;  
          count--;  
     }     
     return   __res;  
}

1、这两个函数的差别其实还是挺大的,差别在这里:    
    
对于memcmp(),如果两个字符串相同而且count大于字符串长度的话,memcmp不会在/0处停下来,会继续比较/0后面的内存单元,直到_res不为零或者达到count次数。     
     对于strncmp(),由于((__res   =   *cs   -   *ct++)   !=   0   ||   !*cs++)的存在,比较必定会在最短的字符串的末尾停下来,即使count还未为零。具体的例子:     
          char   a1[]="ABCD";  
          char   a2[]="ABCD";      
     对于memcmp(a1,a2,10),memcmp在两个字符串的/0之后继续比较  
     对于strncmp(a1,a2,10),strncmp在两个字符串的末尾停下,不再继续比较。      
  所以,如果想使用memcmp比较字符串,要保证count不能超过最短字符串的长度,否则结果有可能是错误的。

2、strncmp("abcd",   "abcdef",   6)   =   0。比较次数是一样的:  
     memcmp:在比较到第5个字符也就是'/0',*su1   -   *su2的结果显然不等于0,所以满足条件跳出循环,不会再进行后面的比较。我想在其他情况下也一样。  
     strncmp:同样的道理再比较到第5个字符时结束循环,其实strncmp中“!*cs++”完全等同于“!*ct++”,其作用仅在于当两个字符串相同的情形下,防止多余的比较次数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值