Comparing Arrays C

Is the defacto method for comparing arrays (in C) to use memcmpfrom string.h?

I want to compare int and double arrays in my unit tests

I am not sure whether to use something like:

double a[] = {1.0, 2.0, 3.0};
double b[] = {1.0, 2.0, 3.0};
size_t n = 3;
if (! memcmp(a, b, n * sizeof(double)))
    /* arrays equal */

or write a type function is_array_equal(a, b, n)to order?

+5
source share
5 answers

memcmpwill make an exact comparison, which is rarely a good idea for a float and will not follow the rule NaN = NaN. For sorting, this is good, but for other purposes you can make a rough comparison, for example:

bool dbl_array_eq(double const *x, double const *y, size_t n, double eps)
{
    for (size_t i=0; i<n; i++)
        if (fabs(x[i] - y[i]) > eps)
            return false;
    return true;
}
+9
source

Replace memsetwith memcmpin in your code and it works.

( ), :

memcmp(a, b, sizeof(a));
+5

memcmp . .


int double, memcmp , , :

struct {
    char c;
    // 1
    int i;
    // 2
}

, 1 2, , , .


. , , . .

- NaN. IEEE754 , , NaN , . , :

#include <stdio.h>
#include <string.h>

int main (void) {
    double d1 = 0.0 / 0.0, d2 = d1;

    if (d1 == d2)
        puts ("Okay");
    else
        puts ("Bad");

    if (memcmp (&d1, &d2, sizeof(double)) == 0)
        puts ("Okay");
    else puts
        ("Bad");

    return 0;
}

Bad
Okay

.

- . , , , memcmp , .

/ d1 d2 :

 double d1 = 0.0, d2 = -d1;

.


, , , , . , , ?

, . ISO , ( /) , , , .

, , - .

( ). ISO , .

, memcmp .

+5

, , memcmp, memset. . , memcmp .

+3

memcmp

memset

can be compared without using memcmp as follows. the same can be changed for different data types.

int8_t array_1[] = { 1, 2, 3, 4 }
int8_t array_2[] = { 1, 2, 3, 4 }

uint8_t i;
uint8_t compare_result = 1;

for (i = 0; i < (sizeof(array_1)/sizeof(int8_t); i++)
{
 if (array_1[i] != array_2[i])
  {
   compare_result = 0;
   break;
  }
}
+2
source

All Articles