温馨提示×

c语言memcmp函数怎么使用

小亿
121
2023-08-04 23:58:23
栏目: 编程语言

memcmp函数是C语言中的库函数,用于比较两个内存块的内容。

该函数的原型如下:

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

其中,ptr1ptr2是要比较的内存块的起始地址,num是要比较的字节数。

函数返回值有三种情况:

  • 如果ptr1ptr2指向的内存块内容相等,则返回0;

  • 如果ptr1指向的内存块内容大于ptr2指向的内存块内容,则返回一个正数;

  • 如果ptr1指向的内存块内容小于ptr2指向的内存块内容,则返回一个负数。

以下是一个使用memcmp函数的例子:

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

输出结果为:

str1 and str2 are equal.
str1 is less than str3.

注意,memcmp函数比较的是内存块的内容,而不是字符串的内容,因此在比较字符串时需要考虑字符串的结束符\0。通常使用sizeof运算符获取内存块的大小来保证比较的字节数正确。

0