约 1590 字

约 8 分钟

#C 语言标准库函数 memcmp

/*********************************************
 * @brief 比较两个内存块里的数据是否相同
 * @param lhs 要比较的内存块
 * @param rhs 要比较的内存块
 * @param count 内存块的字节数
 * @return 内存块的差异
 ********************************************/
int memcmp(const void* lhs, const void* rhs, size_t count);

说明

比较两个内存块里的数据是否相同。

参数

  • lhs - 要比较的内存块
  • rhs - 要比较的内存块
  • count - 内存块的字节数

返回值

  • 如果内存块相同,则返回 0
  • 如果内存块不同,则返回 lhs[i] - rhs[i],i 是第一个不同字节的索引
    • 返回负值说明按照字典序 lhs 在 rhs 之前
    • 返回正值说明按照字典序 lhs 在 rhs 之后

#示例

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define N 5

int main(void)
{
    uint8_t lhs[N] = {10, 21, 33, 45, 66};
    uint8_t rhs[N] = {10, 21, 84, 32, 17};

    printf("%d\n", memcmp(lhs, rhs, N));   // 输出 -51,即 33 - 84

    return 0;
}

运行结果:

-51

#推荐阅读

#参考标准

  • C23 standard (ISO/IEC 9899:2024):
    • 7.24.4.1 The memcmp function (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
    • 7.24.4.1 The memcmp function (p: 266)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.24.4.1 The memcmp function (p: 365)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.21.4.1 The memcmp function (p: 328)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.11.4.1 The memcmp function

更新: 2025/10/25

作者: PlanC

创建: 2025/7/12