Mike Henke
Mike Henke

Reputation: 643

Checking if two arrays are equal - C

How would I go about checking the equality of two arrays using memcmp?

bool array_is_equal(const void *array_one, void *array_two, const size_t elem_size, const size_t elem_count)

I have something like this:

int i;
for(i = 0; i < elem_count; i++){
    if(memcmp(array_one, array_two, elem_size) == 0) {
        return true;
    }
    i++;
 }

return false;

with elem_size being the number of bytes each array element uses in array one

Upvotes: 4

Views: 3904

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

If all you care about is binary equality of two array objects, then you don't even need a cycle

bool array_is_equal(const void *array_one, void *array_two, 
                    const size_t elem_size, const size_t elem_count)
{
  return memcmp(array_one, array_two, elem_count * elem_size) == 0;
}

It is not clear though why array array_two is suddenly non-const (while array array_one is const). And there's not much point in declaring elem_size and elem_count as const (aside from fairly cosmetic considerations).

Upvotes: 9

anotherdev
anotherdev

Reputation: 2567

Since your elements can be anything: an int8_t, a pointer, a double pointer on anything; you need a comparison function specific to the type of element stored.

Imagine that your element is a char *:The 2 strings are identical, but the 2 addresses are different.

You need to give a pointer function on the comparison function, to your function array_is_equal.

For example:

bool array_is_equal(const void *array_one, void *array_two, const size_t elem_size, const size_t elem_count, bool (*comparison_fn)(void *, void *)); 

The comparison for strings:

bool compare_string(void *str1, void *str2) {
  return !!strcmp((char *) str1, (char *)str2);
}

The comparison for a custom struct: bool compare_mystruct(void *p1, void *p2) { bool ret = true; mystryct *s1 = (mystruct *) p1; mystryct *s2 = (mystruct *) p2;

  if(ret) ret = compare_string(p1->str1, p2->str1);
  if(ret) ret = compare_string(p1->str2, p2->str2);
  if(ret) ret = compare_int(p1->int1, p2->int1);

  return ret;
}

Upvotes: 0

Related Questions