The String/Memory Comparision Function memcmp in C/C++


memcmp is a standard library function in C and C++ that compares two blocks of memory byte by byte. It’s declared in the header in C++ and the <string.h> header in C.

Syntax of memcmp

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

Parameters of memcmp

  • ptr1: Pointer to the first block of memory.
  • ptr2: Pointer to the second block of memory.
  • num: Number of bytes to compare.

Return Value of memcmp

  • 0: The memory blocks are equal.
  • > 0: The first differing byte in ptr1 is greater than in ptr2.
  • < 0: The first differing byte in ptr1 is less than in ptr2.

Example C++ of memcmp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>
 
int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";
    char str3[] = "World";
 
    // Compare first two strings
    if (memcmp(str1, str2, sizeof(str1)) == 0) {
        std::cout << "str1 and str2 are equal." << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal." << std::endl;
    }
 
    // Compare first and third string
    if (memcmp(str1, str3, sizeof(str1)) < 0) {
        std::cout << "str1 is less than str3." << std::endl;
    } else {
        std::cout << "str1 is greater than or equal to str3." << std::endl;
    }
 
    return 0;
}
#include <iostream>
#include <cstring>

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

    // Compare first two strings
    if (memcmp(str1, str2, sizeof(str1)) == 0) {
        std::cout << "str1 and str2 are equal." << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal." << std::endl;
    }

    // Compare first and third string
    if (memcmp(str1, str3, sizeof(str1)) < 0) {
        std::cout << "str1 is less than str3." << std::endl;
    } else {
        std::cout << "str1 is greater than or equal to str3." << std::endl;
    }

    return 0;
}

Key Notes:
It compares raw memory, so it is not limited to strings or characters, and can be used for other data types, such as arrays of integers.

Since it compares memory byte by byte, the function doesn’t take into account the data type or encoding. For strings, use strcmp if you want to compare them as null-terminated strings.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
392 words
Last Post: The minpoll and maxpoll in Network Time Protocol (NTP)

The Permanent URL is: The String/Memory Comparision Function memcmp in C/C++

Leave a Reply