C library - memcmp() function



The C library memcmp() function can be used to compare two blocks of memory. In general, it is used to compare the binary data or raw data.

Here, memcmp() accepts three variable as parameters that compares the first n bytes of memory area str1 and memory area str2.

Syntax

Following is the syntax of the C library memcmp() function −

int memcmp(const void *str1, const void *str2, size_t n)

Parameters

This function accepts the following parameters−

  • str1 − This is the pointer to a block of memory.

  • str2 − This parameter define a pointer to the block of memory.

  • n − This parameter define the number of bytes to be compared.

Return Value

This function returns integer values in three different cases −

  • If the return value < 0, it indicates str1 is less than str2.

  • If the return value > 0, it indicates str2 is less than str1.

  • If the return value == 0, it represents str1 is equivalent to the str2.

Example 1

Following is the C library program that illustrates the usage of memcmp() function.

#include <stdio.h>
#include <string.h>

int main () 
{
   char str1[15];
   char str2[15];
   int ret;

   memcpy(str1, "abcdef", 6);
   memcpy(str2, "ABCDEF", 6);

   ret = memcmp(str1, str2, 5);

   if(ret > 0) {
      printf("str2 is less than str1");
   } 
   else if(ret < 0) {
      printf("str1 is less than str2");
   } 
   else {
      printf("str1 is equal to str2");
   }
   return(0);
}

Output

The above code produce the following result−

str2 is less than str1

Example 2

In the below program, we utilize two array integers to check whether it's equal or unequal.

#include <stdio.h>
#include <string.h>

int main() {
   int arr1[] = {1, 2, 3, 4, 5};
   int arr2[] = {1, 2, 3, 4, 6};

   int result = memcmp(arr1, arr2, sizeof(arr1));

   if (result == 0) {
       printf("Arrays are equal\n");
   } else {
       printf("Arrays are not equal\n");
   }
    return 0;
}

Output

On execution of above code, we get the following result −

Arrays are not equal

Example 3

Here, we create an integer values as string and apply the if-else-if statement to check whether the strings are greater, lesser, or equal.

#include <stdio.h>
#include <string.h>

int main() {
   char str1[] = "12345678901400345678";
   char str2[] = "1234567";

   int result = memcmp(str1, str2, 10);

   if (result < 0) {
       printf("First is less than second.\n");
   } else if (result == 0) {
       printf("First is equal to second.\n");
   } else {
       printf("First is greater than second.\n");
   }
    return 0;
}

Output

After executing the code, we get the following result −

First is greater than second.
Advertisements