Compares memory locations.
int memcmp(const void *str1 , const void *str2 , size_t n );
Compares the first n bytes of str1 and str2.
Does not stop comparing even after the null character.
Returns zero if the first n bytes of str1 and str2 are equal.
Returns less than zero or greater than zero if str1 is less than or greater than str2 respectively.
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
This function has the following parameter.
Returns an integral value indicating the relationship between the content of the memory blocks.
#include <stdio.h>
#include <string.h>
/*w w w .j av a 2s . c o m*/
int main (){
char buffer1[] = "this is a test";
char buffer2[] = " ";
int n;
n=memcmp ( buffer1, buffer2, sizeof(buffer1) );
if (n>0)
printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
else if (n<0)
printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
else
printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);
return 0;
}
The code above generates the following result.
#include <stdio.h>
#include <string.h>
/* w ww .ja va 2s .c om*/
void demo(const char* lhs, const char* rhs, size_t sz)
{
for(size_t n = 0; n < sz; ++n) putchar(lhs[n]);
int rc = memcmp(lhs, rhs, sz);
if(rc == 0)
printf(" compares equal to ");
else if(rc < 0)
printf(" precedes ");
else if(rc > 0)
printf(" follows ");
for(size_t n = 0; n < sz; ++n) putchar(rhs[n]);
puts(" in lexicographical order");
}
int main(void)
{
char a1[] = {'a','b','c'};
char a2[sizeof a1] = {'a','b','d'};
demo(a1, a2, sizeof a1);
demo(a2, a1, sizeof a1);
demo(a1, a1, sizeof a1);
}
The code above generates the following result.