首页 > 编程知识 正文

memcmp比较两个数组,memcmp和strcmp的区别

时间:2023-05-04 14:43:15 阅读:257453 作者:900

memcmp()用于数组比较 C++ Reference:

链接: cstring之memcmp.
(http://www.cplusplus.com/reference/cstring/memcmp/)
示例给出了一种类似strcmp的用法,可以用它来比较字符串……

Example /* memcmp example */#include <stdio.h>#include <string.h>int main (){ char buffer1[] = "DWgaOtP12df0"; char buffer2[] = "DWGAOTP12DF0"; int n; n=memcmp ( buffer1, buffer2, sizeof(buffer1) ); if (n>0) printf ("'%s' is greater than '%s'.n",buffer1,buffer2); else if (n<0) printf ("'%s' is less than '%s'.n",buffer1,buffer2); else printf ("'%s' is the same as '%s'.n",buffer1,buffer2); return 0;} 结果

‘DWgaOtP12df0’ is greater than ‘DWGAOTP12DF0’.
DWgAOtp12Df0 is greater than DWGAOTP12DF0 because the first non-matching character in both words are ‘g’ and ‘G’ respectively, and ‘g’ (103) evaluates as greater than ‘G’ (71).

重点来了,除此以外,memcmp还可以—— 可以比较两个int数组里面的元素是否相同 memcmp(a,b,sizeof(a)); //int a[],b[] 都相同则返回值为0。

简单写一下测测:

示例代码 #include <stdio.h>#include <string.h>int main() { int a[10]={1,2,3,4}; int A[10]={1,2,3,4}; int b[10]={5,6,7,8}; printf("%dn",memcmp(a,b,sizeof(a))); printf("%dn",memcmp(a,A,sizeof(a))); printf("%dn",memcmp(b,a,sizeof(a))); return 0;} 运行结果

tbc.

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