memcmp() - Buffer Manipulation Function

How to compare two blocks of memory in C++?


memcmp() manipulation function compares the first "count" characters of buffers, "str1" and "str2". It returns an integer value after comparing the two blocks of memory.


int *memcmp(void *str1, void *str2, size_t count);

The following table lists the possible meanings for the value returned by "memcmp()"
Value Meaning
Less than Zero str1 is less than str2
Zero str1 is equal to str2
Greater than Zero str1 is greater than str2

Example :

#include <stdio.h>
#include <string.h>
int main()
char str1[20]="Hscript";
char str2[20]="Hscripts";
int retval;
r = memcmp( str1, str2, strlen(str1)+1 );
{ printf("string1 is greater than string2\n ");}
else if(r<0)
{printf("string1 is less than string2\n");}
{printf("string1 is equal to string2\n");}
return 0;

Result :

string1 is less than string2

In the above example, this manipulation function is used with "count" value being set to the length of the buffer "str1". By setting this count value, it compares the two blocks of memory.

C++ Tutorial

Ask Questions

Ask Question