---
title: memcmp
description: "比较两块内存区域的内容，逐字节进行比较。如果两块内存的内容不同，返回它们的差异；如果相同，则返回0。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0207.html
sourcePath: /source/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0207.html
indexId: 8ab0ed4153b48571341e9f9534257f065daa08d1bce64a24917d9f201cf7e10576
---
# memcmp

#### 函数功能

比较两块内存区域的内容，逐字节进行比较。如果两块内存的内容不同，返回它们的差异；如果相同，则返回0。


#### 函数定义

```
int memcmp(const void *ptr1, const void *ptr2, size_t num);
```


#### 参数说明

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| ptr1 | 指向第一块内存的指针。 | 非空指针，指向有效内存，至少有num字节可访问。 | 输入 |
| ptr2 | 指向第二块内存的指针。 | 非空指针，指向有效内存，至少有num字节可访问。 | 输入 |
| num | 要比较的字节数。 | 非负数，不超过实际内存大小。 | 输入 |


#### 返回值

- 成功：

  - 如果两块内存相同，返回0。
  - 如果ptr1小于ptr2，返回-1。
  - 如果ptr1大于ptr2，返回1。
- 失败：对标开源Glibc，不返回特殊异常值。

比较是逐字节进行的，直到发现不同字节或比较完num字节。


#### 示例

```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, World!";
char str3[] = "Hello, World";
int result1 = memcmp(str1, str2, sizeof(str1));
if (result1 == 0) {
printf("str1 and str2 are equal\n");
} else {
printf("str1 and str2 are not equal\n");
}
int result2 = memcmp(str1, str3, sizeof(str1));
if (result2 != 0) {
printf("str1 and str3 are not equal\n");
} else {
printf("str1 and str3 are equal\n");
}
return 0;
}
```

运行结果：

```
str1 and str2 are equal
str1 and str3 are not equal
```
