memcmp
Function Usage
Compares the contents of two memory blocks byte by byte. If the contents of the two memory blocks are different, the difference is returned. Otherwise, 0 is returned.
Function Syntax
int memcmp(const void *ptr1, const void *ptr2, size_t num);
Parameters
Parameter |
Description |
Value Range |
Input/Output |
|---|---|---|---|
ptr1 |
Pointer to the first memory block. |
Non-null pointer to a valid memory block, with at least num bytes accessible. |
Input |
ptr2 |
Pointer to the second memory block. |
Non-null pointer to a valid memory block, with at least num bytes accessible. |
Input |
num |
Number of bytes to be compared. |
Non-negative number that does not exceed the memory size. |
Input |
Return Value
- Success:
- If the contents of the two memory blocks are the same, 0 is returned.
- If ptr1 is less than ptr2, -1 is returned.
- If ptr1 is greater than ptr2, 1 is returned.
- Failure: See those of open source glibc. No other exception values will be returned.
The comparison is performed byte by byte until a difference is found or all the num bytes are compared.
Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, World!";
char str3[] = "Hello, World";
int result1 = memcmp(str1, str2, sizeof(str1));
if (result1 == 0) {
printf("str1 and str2 are equal\n");
} else {
printf("str1 and str2 are not equal\n");
}
int result2 = memcmp(str1, str3, sizeof(str1));
if (result2 != 0) {
printf("str1 and str3 are not equal\n");
} else {
printf("str1 and str3 are equal\n");
}
return 0;
}
Output:
str1 and str2 are equal str1 and str3 are not equal
Parent topic: Function Syntax