首页 > 编程知识 正文

memcmp和strcmp的区别,memcpy头文件

时间:2023-05-06 00:53:18 阅读:257458 作者:514



原型  int memcmp(const void *buf1, const void *buf2, unsigned int count);


参数 buf 1 - 比较串1
buf2  - 比较串2
count - 比较字节数


功能 比较内存区域buf1和buf2的前count个字节区分字母的大小写。


返回值 当buf1<buf2时,返回值<0
 
当buf1=buf2时,返回值=0
 
当buf1>buf2时,返回值>0


隐患 请看下面的代码
#include <iostream.h>#include <string.h>typedef struct padding_type {<span style="white-space:pre"></span>short m1;<span style="white-space:pre"></span>int m2;} padding_type_t;int main(){<span style="white-space:pre"></span>padding_type_t a,b;<span style="white-space:pre"></span>a.m1=0;<span style="white-space:pre"></span>a.m2=0;<span style="white-space:pre"></span>memset(&b, 0, sizeof(b));<span style="white-space:pre"></span>if (0 == memcmp(&a, &b, sizeof(a))) <span style="white-space:pre"></span>{<span style="white-space:pre"></span>cout<<"Equal!n";<span style="white-space:pre"></span>}  else <span style="white-space:pre"></span>{  <span style="white-space:pre"></span>cout<<"No equal!n";<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return 0;}

结果是什么?
No equal! 


为什么是这样呢?其实有经验的开发都会立刻反应到,这是由于对齐造成的。
没错,就是因为struct padding_type->m1的类型是short型,而m2的类型是int型,根据自然对齐的原则。padding_type的每个成员需要对齐到4字节。因此编译器会在m1后面插入2个padding字节,而padding的字节的值是随机的。也就是说a中的padding 字节的值是随机的,而b中的padding则被清零。所以当使用memcmpy去比较这两个结构体时,返回值是不等。

从这个例子,我们要记住,在对结构体进行比较时,不要使用字节比较,如memcmp。除非你人为保证了这些对齐的padding字节被清零了。否则,会得到意想不到的结果。



版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。