Easy Tutorial
❮ C Arrays C Function Ferror ❯

C Library Function - memcmp()

C Standard Library - <string.h>

Description

The C library function int memcmp(const void *str1, const void *str2, size_t n) compares the first n bytes of the memory areas str1 and str2.

Declaration

Following is the declaration for the memcmp() function.

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

Parameters

Return Value

Example

The following example demonstrates the use of the 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);
}

Let's compile and run the above program, which will produce the following result:

str2 is less than str1

C Standard Library - <string.h>

❮ C Arrays C Function Ferror ❯