Compare If Two Arrays Are Equal

Hello,

I am trying to create an if statement to compare if two arrays are exactly the same.
Why is my code not working?

char array_1 [4] = "AAAA";
char array_2 [4] = "AAAA";

void setup() {

Serial.begin(9600);
}

void loop() {

if (array_1 == array_2) {
Serial.println("Match");
}

else{
Serial.println("No Match");
}

delay(5000);

}

Thank you for any help.

To compare two arrays, we need to check all the individual element, so in general, we need something like this.

for (size_t i = 0; i < 4; i++) {
  if (array_1[i] != array_2[i]) {
    // No match.
  }
}

In this particular case, you could also consider to use the strcmp function, you have to increase the array sizes by one though, to make room for the terminiation character.

if (strcmp(array_1, array_2) == 0))
  // they are equal.

As the arrays are C style strings you can use strcmp() to compare them

if (strcmp(array_1, array_2) == 0)
{
  Serial.println("Match");
}

There is also memcmp which works on any data type and not "just" strings / char arrays..

@kwalking
first,
please activate the compiler warnings in your IDE. Your sketch gives you two warnings:

C:\Daten\myrepository\Arduino\Forum no SVN\sketch_sep11a\sketch_sep11a.ino:1:20: warning: initializer-string for array of chars is too long [-fpermissive]
 char array_1 [4] = "AAAA";
                    ^~~~~~
C:\Daten\myrepository\Arduino\Forum no SVN\sketch_sep11a\sketch_sep11a.ino:2:20: warning: initializer-string for array of chars is too long [-fpermissive]
 char array_2 [4] = "AAAA";
                    ^~~~~~

"AAAA" will need 5 bytes, so it doesn't fit in your variable.

this should compile without warnings:

char array_1[4] {'A', 'A', 'A', 'A'};
char array_2[4] {'A', 'A', 'A', 'A'};

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (!memcmp(array_1, array_2, 4))
  {
    Serial.println("Match");
  }
  else 
  {
    Serial.println("No Match");
  }
  delay(5000);
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.