Reputation: 459
I have to check equality of two arrays(1-D) with integer elements.
I understand that there is no direct comparison way. So i'm doing basic iteration and checking for equality of each element.
for ( int i = 0 ; i < len ; i++) {
// Equality check
What is the most efficient way to test equality of arrays in C ? Can i get away with loops(for ..) somehow ?
Upvotes: 5
Views: 3579
Reputation: 4214
You can refer for loop method
Or else memcmp
is also an efficient way of comparing array.
Refer memcmp
int memcmp(const void *s1, const void *s2, size_t n);
You can compare first n byte with this function
int array1[5],array2[5];
int x = memcmp(array1, array2, sizeof(array1));
If array size is different then:
sizeof(array1) is equal to sizeof(array2), it returns zero.
How to use memcmp
? Answer is also on SO.
REMEMBER memcmp
is only useful when both memory element or arraysize are equal
Upvotes: 1
Reputation: 36617
As others have said, using memcmp()
is effective.
A general answer, assuming actual arrays, is
int is_equal = sizeof(array1) == sizeof(array2) && !memcmp(array1, array2, sizeof(array1));
If the arrays are supplied as pointer arguments to a function, the size information is lost, and needs to be provided separately.
int IsEqual(void *array1, void *array2, size_t size1, size_t size2)
{
return size1 == size2 && !memcmp(array1, array2, size1);
}
int main()
{
int arr1[] = { /* whatever */ };
int arr2[] = { /* whatever */ };
is_equal = IsEqual(arr1, arr2, sizeof(arr1), sizeof(arr2));
return 0;
}
or, preserve type information (i.e. knowledge of working with an array of int
) as late as possible before converting to void
pointers, and work with number of elements.
int IsEqual2(int array1[], int array2[], size_t n1, size_t n2)
{
/* n1 and n2 are number of ints in array1 and array2 respectively */
return n1 == n2 && !memcmp(array1, array2, n1 * sizeof(int));
}
int main()
{
int arr1[] = { /* whatever */ };
int arr2[] = { /* whatever */ };
is_equal = IsEqual2(arr1, arr2, sizeof(arr1)/sizeof(*arr1), sizeof(arr2)/sizeof(*arr2));
return 0;
}
Upvotes: 2