首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

memcmp与strncmp的差异

2013-01-01 
memcmp与strncmp的区别一、memcmp含义Compare characters in two buffers.int memcmp(const void*buf1,cons

memcmp与strncmp的区别

一、memcmp含义

Compare characters in two buffers.

int memcmp(    const void*buf1,    const void* buf2,    size_tcount );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 ValueRelationship of First count Bytes of buf1 and buf2        < 0        buf1 less thanbuf2        0         buf1 identical tobuf2

> 0

buf1 greater thanbuf2

 二、memcmp与strncmp的区别

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++”,其作用仅在于当两个字符串相同的情形下,防止多余的比较次数。

热点排行