C Online Compiler
Example: Array Equality Check (memcmp) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Array Equality Check (memcmp) #include <stdio.h> #include <string.h> // For memcmp #include <stdbool.h> // For using bool type // Function to compare two character arrays (strings) for equality using memcmp bool areCharArraysEqualMemcmp(const char arr1[], size_t size1, const char arr2[], size_t size2) { // Step 1: Check if the sizes of the arrays are different if (size1 != size2) { return false; // Arrays cannot be equal if their sizes differ } // Step 2: Use memcmp to compare the memory blocks // memcmp returns 0 if the blocks are identical return memcmp(arr1, arr2, size1) == 0; } // Example for integer arrays (with a caveat) bool areIntArraysEqualMemcmp(const int arr1[], size_t size1, const int arr2[], size_t size2) { if (size1 != size2) { return false; } // memcmp compares byte-by-byte. This works for simple integer arrays // but be cautious with structs, padding, or cross-platform comparisons. return memcmp(arr1, arr2, size1 * sizeof(int)) == 0; } int main() { // Example 1 (Char Arrays): Equal char str1[] = "hello"; size_t len1 = strlen(str1); // Excludes null terminator for comparison of content char str2[] = "hello"; size_t len2 = strlen(str2); // Example 2 (Char Arrays): Unequal char str3[] = "world"; size_t len3 = strlen(str3); // Example 3 (Int Arrays): Equal int intArr1[] = {1, 2, 3, 4, 5}; size_t intSize1 = sizeof(intArr1) / sizeof(intArr1[0]); int intArr2[] = {1, 2, 3, 4, 5}; size_t intSize2 = sizeof(intArr2) / sizeof(intArr2[0]); // Example 4 (Int Arrays): Unequal (different element) int intArr3[] = {1, 2, 3, 4, 99}; size_t intSize3 = sizeof(intArr3) / sizeof(intArr3[0]); printf("Comparing char arrays \"%s\" and \"%s\": %s\n", str1, str2, areCharArraysEqualMemcmp(str1, len1, str2, len2) ? "Equal" : "Not Equal"); printf("Comparing char arrays \"%s\" and \"%s\": %s\n", str1, str3, areCharArraysEqualMemcmp(str1, len1, str3, len3) ? "Equal" : "Not Equal"); printf("Comparing int arrays {1,2,3,4,5} and {1,2,3,4,5}: %s\n", areIntArraysEqualMemcmp(intArr1, intSize1, intArr2, intSize2) ? "Equal" : "Not Equal"); printf("Comparing int arrays {1,2,3,4,5} and {1,2,3,4,99}: %s\n", areIntArraysEqualMemcmp(intArr1, intSize1, intArr3, intSize3) ? "Equal" : "Not Equal"); return 0; }
Output
Clear
ADVERTISEMENTS