The memcmp
function in C is used to compare the contents of two memory areas byte by byte. The return value indicates their relationship.
memcmp Function Header File
The header file for the memcmp
function is <string.h>
. Before using the memcmp
function, ensure that this header file is included in your C code:
#include <string.h>
memcmp Function Prototype
int memcmp(const void *s1, const void *s2, size_t n);
The memcmp
function compares the first n
characters of the object pointed to by s1
with the first n
characters of the object pointed to by s2
;
The comparison is performed byte by byte, from the lowest address to the highest address;
Parameter Description
s1
: A pointer to the first memory block;s2
: A pointer to the second memory block;n
: The number of bytes to compare;
Return Value
The memcmp
function returns an integer greater than, equal to, or less than 0
;
A return value of 0
indicates that the first n
bytes of both memory blocks are completely identical;
The positive or negative return value is calculated based on the difference in byte values:
memcmp = (unsigned char)s1[i] - (unsigned char)s2[i];
memcmp Example Code
Comparing Arrays for Equality
When comparing arrays or structures, ensure the entire object region is covered;
#include <stdio.h>
#include <string.h>
int main() {
int array1[] = { 1, 2, 3, 4, 5};
int array2[] = { 1, 2, 3, 4, 5};
if (memcmp(array1,array2,sizeof(int) * 5) == 0) {
printf("Completely identical.\n");
}else{
printf("Differences exist.");
}
return 0;
}