In this tutorial, you will learn in-depth about C string library function memcmp() with explanation and explicit example.

c string library function memcmp()

memcmp() is the built-in standard library function that is defined in the string library string.h. Therefore, we should include string header library before using it.

#include<string.h>

Function prototype of C string library function memcmp()

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

where,

               str1 = Pointer to the object or block of the memory

              str1 = Pointer to the object or block of the memory

               n = Size of content to be compared in bytes

This function compares the first n characters of the memory block pointed by str1 and str2.

memcmp( ) returns:

  • zero if str1 is equal to str2.
  • Less than zero if str1 is less than str2.
  • Greater than zero if str1 is greater than str2.

Example: Program to demonstrate the use of C string library function memcmp()

/*Use of string library function memcmp()*/

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

int main()
{
 //initializing character array
 char str1[ ] = "Learn python from tyrtoprogram.com";
 char str2[ ] = "Learn C from trytoprogram.com";

 //displaying str1 and str2
 printf("str1 = %s\n", str1);
 printf("str2 = %s\n", str2);

 printf("\nmemcmp( str1, str2, 5 ) = %d\n", memcmp( str1, str2, 5 ));
 printf("\nmemcmp( str1, str2, 15 ) = %d\n", memcmp( str1, str2, 15 ));
 printf("\nmemcmp( str2, str1, 15 ) = %d\n", memcmp( str2, str1, 15 ));

 return 0;
}

[adsense1]

Output

output c memcmp

Explanation

In the above program, specified characters of str1 and str2 are compared.

A comparison is made between the ASCII value of characters.

Since, first 5 characters of both character arrays are same memcmp( str1, str2, 5 ) returns 0.

Similarly, it returns 1 and -1 after the comparison between ASCII values.