memcmp function(Compare Memory Blocks) in C Language – example and detail

In the C Programming Language, the memcmp feature returns a negative, zero, or superb integer depending on whether the first n characters of the object pointed to by using s1 are less than, equal to, or greater than the first n characters of the object pointed to by using s2.

Syntax

The syntax for the memcmp function in the C Language is:

int memcmp(const void *s1, const void *s2, size_t n);

Parameters or Arguments

s1 An array to compare. s2 An array to compare. n The wide variety of characters to compare.

Returns

The memcmp feature returns an integer. The return values are as follows:

Return Value Explanation 0 s1 and s2 are equal Negative integer The stopping personality in s1 used to be much less than the stopping persona in s2 Positive integer The stopping personality in s1 was greater than the stopping character in s2

Required Header

In the C Language, the required header for the memcmp function is:

#include <string.h>

Applies To

In the C Language, the memcmp characteristic can be used in the following versions:

ANSI/ISO 9899-1990

memcmp Example

Let’s appear at an instance to see how you would use the memcmp feature in a C program:

/* Example using memcmp by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
    /* Create a place to store our results */
    int result;

    /* Create two arrays to hold our data */
    char example1[50];
    char example2[50];

    /* Copy two strings into our data arrays
     (These can be any data and do not have to be strings) */
    strcpy(example1, "C memcmp at TechOnTheNet.com");
    strcpy(example2, "C memcmp is a memory compare function");

    /* Compare the two strings provided up to the first 9 characters */
    result = memcmp(example1, example2, 9);

    /* If the two arrays are the same say so */
    if (result == 0) printf("Arrays are the same\n");

    /* Compare the two strings provided up to the first 10 characters */
    result = memcmp(example1, example2, 10);

    /* If the first array is less than the second say so
     (This is because the 'a' in the word 'at' is less than
     the 'i' in the word 'is' */
    if (result < 0) printf("Second array is less than the first\n");

    return 0;
}

When compiled and run, this utility will output:

Arrays are the same
Second array is less than the first

Similar Functions

Other C features that are similar to the memcmp function:

strcmp function strcoll function strncmp feature