Equality Arrays In c

I have to check the equality of two arrays (1-D) with integer elements.

I understand that there is no direct way to compare. So I do a basic iteration and check the equality of each element.

 for ( int i = 0 ; i < len ; i++) {
    // Equality check

What is the most efficient way to check for equality of arrays in C? Can I get away with loops (for ..) somehow?

+4
source share
3 answers

Use the memcmpfunction to compare two arrays of the same length.

int a = memcmp(arr1, arr2, sizeof(arr1));
if(!a)
    printf("Arrays are equal\n");
else
    printf("Arrays are not equal\n");
+5
source

As others have said, use memcmp()is effective.

The general answer assuming valid arrays is

int is_equal = sizeof(array1) == sizeof(array2) && !memcmp(array1, array2, sizeof(array1));

, .

 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;
 }

(.. int) , void .

 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;
 }
+2

memcmp . . memcmp

int memcmp (const void * s1, const void * s2, size_t n);

n

int array1[5],array2[5]; 
int x = memcmp(array1, array2, sizeof(array1));

, :

  • sizeof (array1) sizeof (array2), .
  • sizeof (array1) , sizeof (array2), .
  • sizeof (array1) sizeof (array2), .

    memcmp? SO.

memcmp ,

+1
source

Source: https://habr.com/ru/post/1621924/


All Articles