memcmp
|
定义于头文件
<string.h>
|
||
|
int
memcmp
(
const
void
*
lhs,
const
void
*
rhs,
size_t
count
)
;
|
||
比较由 lhs 和 rhs 指向的对象的前 count 个字节。该比较按字典序进行。
结果的符号取决于对象比较中第一对不同的字节值(均解释为 unsigned char )的差值符号。
如果访问超出 lhs 和 rhs 所指向的任一对象的末尾,则行为未定义。如果 lhs 或 rhs 是空指针,则行为未定义。
目录 |
参数
| lhs, rhs | - | 待比较对象的指针 |
| count | - | 待检验的字节数 |
返回值
若 lhs 在字典序中出现在 rhs 之前,则返回负值。
当 lhs 与 rhs 比较相等,或 count 为零时返回零。
正值表示 lhs 在字典序中出现在 rhs 之后。
注释
此函数读取的是 对象表示 而非对象值,通常仅对字节数组有意义:结构体可能包含值不确定的填充字节,联合体中最后一个存储成员之后的任何字节值不确定,且同一值可能对应类型的两种或多种表示形式(例如 + 0 与 - 0 的不同编码,或 + 0.0 与 – 0.0 的不同编码,以及类型内部的不确定填充位)。
示例
#include <stdio.h> #include <string.h> void demo(const char* lhs, const char* rhs, size_t sz) { for(size_t n = 0; n < sz; ++n) putchar(lhs[n]); int rc = memcmp(lhs, rhs, sz); const char *rel = rc < 0 ? " precedes " : rc > 0 ? " follows " : " compares equal "; fputs(rel, stdout); for(size_t n = 0; n < sz; ++n) putchar(rhs[n]); puts(" in lexicographical order"); } int main(void) { char a1[] = {'a','b','c'}; char a2[sizeof a1] = {'a','b','d'}; demo(a1, a2, sizeof a1); demo(a2, a1, sizeof a1); demo(a1, a1, sizeof a1); }
输出:
abc precedes abd in lexicographical order abd follows abc in lexicographical order abc compares equal to abc in lexicographical order
参考文献
- C23 标准 (ISO/IEC 9899:2024):
-
- 7.24.4.1 memcmp 函数 (p: TBD)
- C17 标准 (ISO/IEC 9899:2018):
-
- 7.24.4.1 memcmp 函数 (页: 266)
- C11 标准 (ISO/IEC 9899:2011):
-
- 7.24.4.1 memcmp 函数 (p: 365)
- C99标准(ISO/IEC 9899:1999):
-
- 7.21.4.1 memcmp函数(页码:328)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.11.4.1 memcmp 函数
参见
|
比较两个字符串
(function) |
|
|
比较两个字符串的指定数量字符
(function) |
|
|
C++ documentation
for
memcmp
|
|