memcmp() function in C++

In this guide, you will learn what is memcmp() function is in C++ programming and how to use it with an example.

1. memcmp() Function Overview

The memcmp() function in C++ is used to compare two blocks of memory and determine if they are the same or if one is lexicographically greater or smaller than the other. It's a part of the C++ <cstring> header. This function compares the first n bytes of the memory areas ptr1 and ptr2.

Signature:

int memcmp(const void* ptr1, const void* ptr2, size_t n);

Parameters:

- ptr1: Pointer to the first memory block.

- ptr2: Pointer to the second memory block.

- n: Number of bytes to be compared.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char buffer1[] = "DWgaOtP12df0";
    char buffer2[] = "DWGAOTP12DF0";

    int n;

    n = memcmp(buffer1, buffer2, sizeof(buffer1));

    if (n > 0) {
        std::cout << "buffer1 is greater than buffer2" << std::endl;
    } else if (n < 0) {
        std::cout << "buffer1 is less than buffer2" << std::endl;
    } else {
        std::cout << "buffer1 is the same as buffer2" << std::endl;
    }

    return 0;
}

Output:

buffer1 is less than buffer2

3. Explanation

In the provided source code:

1. We include the necessary header files: <iostream> for input/output operations and <cstring> for memcmp().

2. Two character arrays, buffer1 and buffer2, are defined.

3. The memcmp() function is used to compare the two buffers.

4. Based on the result of the comparison, we determine if one buffer is greater than, less than, or the same as the other buffer.


Comments