Program To Check If Two Arrays Are Equal Or Not In C
Arrays are fundamental data structures in C for storing collections of elements of the same type. Determining if two arrays are identical is a common task in programming. In this article, you will learn how to effectively compare two arrays for equality in C.
Problem Statement
Two arrays are considered equal if and only if they have the same number of elements and each corresponding element at every index is identical. This comparison is critical in various scenarios, from data validation to state verification in complex applications. Incorrectly comparing arrays can lead to logical errors and unexpected program behavior.
Example
Consider these integer arrays:
-
arrayA:{10, 20, 30} -
arrayB:{10, 20, 30} -
arrayC:{10, 20, 40} -
arrayD:{10, 20}
Here, arrayA and arrayB are equal because they have the same size and identical elements at each position. arrayA and arrayC are not equal due to a differing element at index 2. arrayA and arrayD are not equal because their sizes are different, even though their initial elements match.
Background & Knowledge Prerequisites
To understand array comparison in C, familiarity with the following concepts is helpful:
- C Programming Basics: Fundamental syntax, data types.
- Arrays: How to declare, initialize, and access elements.
- Loops: Especially
forloops, for iterating through array elements. - Conditional Statements:
if-elsefor decision-making. - Functions: Defining and calling functions to encapsulate comparison logic.
- Pointers: Understanding how array names decay to pointers when passed to functions, particularly relevant for
memcmp.
Use Cases or Case Studies
Checking array equality is useful in many programming contexts:
- Data Validation: Ensuring user input matches a predefined set of values or a template.
- State Comparison: In simulation or game development, checking if the current state (represented by an array) matches a target state or a previous state.
- Unit Testing: Verifying that the output of a function (e.g., an array returned by a sorting algorithm) is identical to an expected array.
- Cryptographic Hashing: Although not directly comparing entire arrays, many hashing algorithms involve processing chunks of data that can be treated as arrays, where bit-level equality is paramount.
- Embedded Systems: Comparing sensor readings or control sequences against known patterns for anomaly detection or operational verification.
Solution Approaches
There are primarily two common approaches to check array equality in C: an iterative element-by-element comparison and using the memcmp function for byte-level comparison.
Approach 1: Iterative Element-by-Element Comparison
This is the most straightforward and universally applicable method. It involves comparing the sizes of the arrays first, and if they are equal, then iterating through each element to check for identity.
- Summary: This approach uses a
forloop to compare each element of the two arrays sequentially. It first checks if the array sizes are identical, returningfalseimmediately if they differ. If sizes match, it proceeds to compare elements. - Code Example:
// Array Equality Check (Iterative)
#include <stdio.h>
#include <stdbool.h> // For using bool type
// Function to compare two integer arrays for equality
bool areArraysEqual(int arr1[], int size1, int arr2[], int 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: Iterate through the arrays and compare elements
for (int i = 0; i < size1; i++) {
if (arr1[i] != arr2[i]) {
return false; // Found a differing element, so arrays are not equal
}
}
// Step 3: If loop completes, all elements were identical
return true; // Arrays are equal
}
int main() {
// Example 1: Equal arrays
int arrA[] = {10, 20, 30, 40, 50};
int sizeA = sizeof(arrA) / sizeof(arrA[0]);
int arrB[] = {10, 20, 30, 40, 50};
int sizeB = sizeof(arrB) / sizeof(arrB[0]);
// Example 2: Unequal arrays (different element)
int arrC[] = {10, 20, 30, 40, 55};
int sizeC = sizeof(arrC) / sizeof(arrC[0]);
// Example 3: Unequal arrays (different size)
int arrD[] = {10, 20, 30};
int sizeD = sizeof(arrD) / sizeof(arrD[0]);
printf("Comparing arrA and arrB: %s\\n", areArraysEqual(arrA, sizeA, arrB, sizeB) ? "Equal" : "Not Equal");
printf("Comparing arrA and arrC: %s\\n", areArraysEqual(arrA, sizeA, arrC, sizeC) ? "Equal" : "Not Equal");
printf("Comparing arrA and arrD: %s\\n", areArraysEqual(arrA, sizeA, arrD, sizeD) ? "Equal" : "Not Equal");
return 0;
}- Sample Output:
Comparing arrA and arrB: Equal
Comparing arrA and arrC: Not Equal
Comparing arrA and arrD: Not Equal- Stepwise Explanation:
- The
areArraysEqualfunction takes two arrays and their respective sizes as input. - It first checks if
size1is not equal tosize2. If they differ, the arrays cannot be equal, and the function immediately returnsfalse. - If the sizes are identical, a
forloop iterates from index0up tosize1 - 1. - Inside the loop, it compares
arr1[i]witharr2[i]. If any pair of elements at the same index is not equal, the function returnsfalse. - If the loop completes without finding any differing elements, it means all elements were identical, so the function returns
true.
Approach 2: Using memcmp for Byte-Level Comparison
The memcmp function, part of the library, is designed for comparing blocks of memory. It can be used for arrays, especially character arrays (strings) or when a byte-by-byte comparison is sufficient and appropriate.
- Summary:
memcmpcomparesnbytes of memory pointed to byptr1andptr2. It returns 0 if the memory blocks are identical, a negative value ifptr1's block is lexicographically smaller, and a positive value otherwise. This approach is efficient but requires careful consideration of data types and padding. - Code Example:
// 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;
}- Sample Output:
Comparing char arrays "hello" and "hello": Equal
Comparing char arrays "hello" and "world": Not Equal
Comparing int arrays {1,2,3,4,5} and {1,2,3,4,5}: Equal
Comparing int arrays {1,2,3,4,5} and {1,2,3,4,99}: Not Equal- Stepwise Explanation:
- The
areCharArraysEqualMemcmpfunction (andareIntArraysEqualMemcmp) takes two array pointers and their effective data sizes (in bytes formemcmp) as input. - Similar to the iterative approach, it first checks if the conceptual sizes (
size1,size2) are equal. If not, they are unequal. - If sizes match,
memcmpis called. For character arrays,size1is passed directly as the number of bytes to compare. Forintarrays,size1 * sizeof(int)is passed to compare the total byte footprint of the integer data. memcmpreturns0if the memory regions are identical. The function then returnstrueifmemcmpreturns0, andfalseotherwise.- Important Note for
memcmp: While efficient,memcmpperforms a byte-by-byte comparison. This is perfect forchararrays (strings) but can be problematic for other data types if:- Arrays contain floating-point numbers where bitwise equality might not mean mathematical equality (e.g.,
NaNvalues).
- Arrays contain floating-point numbers where bitwise equality might not mean mathematical equality (e.g.,
int, long, float, etc., the iterative approach is often safer and more explicit regarding type semantics.
Conclusion
Comparing arrays for equality in C is a common and important task. The iterative element-by-element approach provides a robust and type-safe method suitable for all data types, ensuring both size and content identity. For character arrays or specific scenarios where byte-level comparison is desired and safe, memcmp offers a highly efficient alternative. Always consider the data types and potential system-level differences when choosing between these methods.
Summary
- Array Equality: Two arrays are equal if they have the same size and identical elements at every corresponding index.
- Iterative Comparison:
- Compares array sizes first.
- If sizes are equal, loops through and compares each element.
- Robust and type-safe for all data types.
-
memcmpFunction: - Compares specified number of bytes from two memory locations.
- Efficient for
chararrays (strings). - Requires careful use for other data types due to byte-level comparison, which may ignore type semantics, padding, or endianness differences.
- Choosing a Method: Use iterative comparison for general array types to ensure type-semantic equality. Use
memcmpfor character arrays or when byte-exact matching is explicitly required and understood for other types.