memcmp() Function
The memcmp()
function in C compares two blocks of memory and returns an integer indicating their relationship. It examines each byte in the specified number of bytes, providing a result that shows whether the memory areas are identical or which one is greater, without stopping at a null character.
Syntax of memcmp()
int memcmp(const void *ptr1, const void *ptr2, size_t num);
Parameters
Parameter | Description |
---|---|
ptr1 | Pointer to the first memory block to be compared. |
ptr2 | Pointer to the second memory block to be compared. |
num | The number of bytes to compare. |
Return Value
The function returns an integer that indicates the result of the comparison.
- A return value of zero means that the memory blocks are equal.
- A negative value indicates that the first non-matching byte in the first block is less than that in the second block.
- A positive value indicates it is greater (evaluated as unsigned char values).
Additional Details
Unlike strcmp()
, memcmp()
continues comparing even if a null character is encountered. This makes it suitable for comparing both textual and binary data where the presence of null characters does not denote the end of the data.
Examples for memcmp()
Example 1: Comparing Two Identical Strings
This example demonstrates how memcmp()
is used to compare two identical strings. The function returns zero since all compared bytes match.
Program
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, World!";
int result;
result = memcmp(str1, str2, sizeof(str1));
if(result == 0) {
printf("The memory blocks are equal.\n");
} else {
printf("The memory blocks are not equal.\n");
}
return 0;
}
Output:
The memory blocks are equal.
Example 2: Comparing Two Different Strings
This example compares two strings that differ in content. The function examines a specified number of bytes and returns a value that indicates which memory block is considered greater based on the first differing byte.
Program
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Applesauce";
int result;
// Compare only the first 5 bytes
result = memcmp(str1, str2, 5);
if(result == 0) {
printf("The first 5 bytes are equal.\n");
} else if(result < 0) {
printf("The first differing byte in the first block is less than that in the second block.\n");
} else {
printf("The first differing byte in the first block is greater than that in the second block.\n");
}
return 0;
}
Output:
The first 5 bytes are equal.