Cover Image for memcmp() in C
121 views

memcmp() in C

The memcmp() function in C is used to compare two blocks of memory to determine whether they are equal or not. It is often used to compare arrays or data structures, including strings, byte buffers, or any other type of memory block. The function is part of the C Standard Library and has the following prototype:

C
int memcmp(const void *ptr1, const void *ptr2, size_t size);
  • ptr1: A pointer to the first memory block to be compared.
  • ptr2: A pointer to the second memory block to be compared.
  • size: The number of bytes to compare.

The memcmp() function compares the memory blocks pointed to by ptr1 and ptr2 byte by byte for the first size bytes. It returns an integer value:

  • If the memory blocks are equal, it returns 0.
  • If ptr1 is greater than ptr2 (according to their byte values), it returns a positive integer.
  • If ptr1 is less than ptr2 (according to their byte values), it returns a negative integer.

Here’s an example of how to use memcmp():

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

int main() {
    char str1[] = "Hello, World!";
    char str2[] = "Hello, World!";
    char str3[] = "Goodbye, World!";

    int result1 = memcmp(str1, str2, strlen(str1));
    int result2 = memcmp(str1, str3, strlen(str1));

    if (result1 == 0) {
        printf("str1 and str2 are equal.\n");
    } else {
        printf("str1 and str2 are not equal.\n");
    }

    if (result2 == 0) {
        printf("str1 and str3 are equal.\n");
    } else {
        printf("str1 and str3 are not equal.\n");
    }

    return 0;
}

In this example:

  • We compare the strings str1 and str2 using memcmp(), and since they are equal, result1 will be 0.
  • We also compare str1 and str3, which are not equal, so result2 will be nonzero.
  • We then check the results and print whether the strings are equal or not.

memcmp() is often used for comparing binary data or strings where a byte-by-byte comparison is required. It’s important to note that the comparison is done based on byte values, so it’s not suitable for comparing string values based on their lexical order. For string comparisons based on lexical order, you should use functions like strcmp() or strncmp().

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS