memcmp和strncmp函数

一.memcmp函数

 原型:extern int memcmp(void *buf1, void *buf2, unsigned int count);
       
  用法:#include <string.h>
 
  功能:比较内存区域buf1和buf2的前count个字节。
 
  说明:
        当buf1<buf2时,返回值<0
        当buf1=buf2时,返回值=0
        当buf1>buf2时,返回值>0

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main()
 5 {
 6     char *s1="Hello, ACMer!";
 7     char *s2="Hello, acmer!";
 8     int r;
 9     
10     r=memcmp(s1,s2,strlen(s1));
11     if(!r)
12         printf("s1 and s2 are identical");
13     else if(r<0)
14         printf("s1 less than s2");
15     else
16         printf("s1 greater than s2");
17 
18 
19     getchar();
20     return 0;
21 }

二.和strncmp的区别
  对于memcmp(),如果两个字符串相同而且count大于字符串长度的话,memcmp不会在\0处停下来,会继续比较\0后面的内存单元,直到_res不为零或者达到count次数。对于strncmp(),比较必定会在最短的字符串的末尾停下来,即使count还未为零。

posted @ 2013-04-11 12:39  加拿大小哥哥  阅读(664)  评论(0编辑  收藏  举报