国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > memcmp 以获得更好的体验。

# C 语言标准库函数 memcmp

在头文件 string.h 中定义。
/*********************************************
 * @brief 比较两个内存块里的数据是否相同
 * @param lhs 要比较的内存块
 * @param rhs 要比较的内存块
 * @param count 内存块的字节数
 * @return 内存块的差异
 ********************************************/
int memcmp(const void* lhs, const void* rhs, size_t count);

!subtitle:说明

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

!subtitle:参数

  • lhs - 要比较的内存块

  • rhs - 要比较的内存块

  • count - 内存块的字节数

!subtitle:返回值

  • 如果内存块相同,则返回 0

  • 如果内存块不同,则返回 lhs[i] - rhs[i]i 是第一个不同字节的索引

    • 返回负值说明按照字典序 lhsrhs 之前

    • 返回正值说明按照字典序 lhsrhs 之后

# 示例

#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-11-27 09:38:09 创建于: 2025-11-27 09:38:09