1. Introduction to memcmp()
1. Function prototype
int memcmp(const void *str1, const void *str2, size_t n));
2. Parameters
- str1 -Pointer to the memory block.
- str2 -Pointer to the memory block.
- n -the number of bytes to be compared
3. Function
Compare the first n bytes of storage area str1 and storage area str2, mainly for comparing character strings.
4. Header files
#include <string.h>
5. Return value
- From left to right , compare n characters one by one according to the ASCII code value until a different character appears.
- If the return value is <0, it means str1 is less than str2.
- If the return value> 0, it means that str2 is less than str1.
- If the return value = 0, it means that str1 is equal to str2.
Two, memcmp() usage
The memcmp function is mainly used to compare strings.
The specific code is as follows:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *a = "English";
char *b = "ENGLISH";
char *c = "english";
char *d = "English";
printf("memcmp(a, b):%d\n", memcmp(a, b, 7));//字符串之间的比较
printf("memcmp(a, c):%d\n", memcmp(a, c, 7));
printf("memcmp(a, d):%d\n", memcmp(a, d, 7));
printf("memcmp(a, \"English\"):%d\n", memcmp(a, "English", 7));
printf("memcmp(&a[2], \"g\"):%d\n", memcmp(&a[2], "g", 1)); //单个字符的比较
return 0;
}
The results are as follows:
memcmp(a, b):1
memcmp(a, c):-1
memcmp(a, d):0
memcmp(a, "English"):0
memcmp(&a[2], "g"):0