C++官网参考链接:https://cplusplus.com/reference/cstring/memcmp/
函数
<cstring>
memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
比较两个内存块
将ptr1指向的内存块的第一个num个字节与ptr2指向的第一个num个字节进行比较,如果它们都匹配则返回0,如果不匹配则返回一个不同于0的值,表示哪个值更大。
注意,与strcmp不同的是,该函数在找到空字符后不会停止比较。
形参
ptr1
指向内存块的指针。
ptr2
指向内存块的指针。
num
要比较的字节数量。
返回值
返回一个整数值,表示内存块中的内容之间的关系:
return value | indicates |
---|---|
<0 | the first byte that does not match in both memory blocks has a lower value in ptr1 than in ptr2 (if evaluated as unsigned char values) (在两个内存块中不匹配的第一个字节(如果计算为unsigned char值)在ptr1中的值比在ptr2中的值小) |
0 | the contents of both memory blocks are equal (两个内存块的内容相等) |
>0 | the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 (if evaluated as unsigned char values) (在两个内存块中不匹配的第一个字节(如果计算为unsigned char值)在ptr1中的值比在ptr2中的值大) |
用例
/* 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大于DWGAOTP12DF0,因为两个单词中第一个不匹配的字符分别是'g'和'G',并且'g'(103)的计算结果大于'G'(71)。