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("%d\n",memcmp(a,b,sizeof(a)));
printf("%d\n",memcmp(a,A,sizeof(a)));
printf("%d\n",memcmp(b,a,sizeof(a)));
return 0;
}
运行结果
tbc.