memcmp is a standard library function in C and C++ that compares two blocks of memory byte by byte. It’s declared in the
Syntax of memcmp
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
#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.
C/C++ Programming
- Understanding std::transform_reduce in Modern C++
- Implement a Lock Acquire and Release in C++
- Detecting Compile-time vs Runtime in C++: if consteval vs std::is_constant_evaluated()
- C++ Forward References: The Key to Perfect Forwarding
- Understanding dynamic_cast in C++: Safe Downcasting Explained
- C vs C++: Understanding the restrict Keyword and its Role in Optimization
- C++ Lvalue, Rvalue and Rvalue References
- C++ assert vs static_assert
- Why auto_ptr is Deprecated in C++?
- C++ What is the consteval? How is it different to const and constexpr?
- Tutorial on C++ std::move (Transfer Ownership)
- const vs constexpr in C++
- Tutorial on C++ Ranges
- Tutorial on C++ Smart Pointers
- Tutorial on C++ Future, Async and Promise
- The Memory Manager in C/C++: Heap vs Stack
- The String Memory Comparision Function memcmp() in C/C++
- Modern C++ Language Features
- Comparisions of push_back() and emplace_back() in C++ std::vector
- C++ Coding Reference: is_sorted_until() and is_sorted()
- C++ Coding Reference: iota() Setting Incrementing Values to Arrays or Vectors
- C++ Coding Reference: next_permutation() and prev_permutation()
- C++ Coding Reference: count() and count_if()
- C++ Code Reference: std::accumulate() and Examples
- C++ Coding Reference: sort() and stable_sort()
- The Next Permutation Algorithm in C++ std::next_permutation()
–EOF (The Ultimate Computing & Technology Blog) —
385 wordsLast Post: The minpoll and maxpoll in Network Time Protocol (NTP)
Next Post: Excel Tutorial: SUMIF Function