A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_memcmp.htm below:

C library - memcmp() function

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

Return Value

This function returns integer values in three different cases −

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.

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4