0

I wrote this little program to test converting and comparing 2 char with each other. With some help from here i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:

char code[4] = {'1','2','3','4'};
char strcode[5];
char pass[4] = {'1','2','3','4'};
char strpass[5];


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


void loop()
{
    memcpy(strcode, code, 5);
    strcode[4] = '\0';
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
    memcpy(strpass, pass, 5);
    strpass[4] = '\0';
    Serial.println(strpass);
    Serial.println("donepass");
    if (strpass == strcode)
    {
        Serial.println("yes");
    }
    else
    {
        Serial.println("no");
    }
}

I get this in my serial monitor:

1234
done
1234
donepass
no

Why is this not equal to each other?

2

You cannot compare char arrays with ==. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.

C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).

Comparing two char array variables with == is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.

There's various functions for doing that depending on how you want to compare.

strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

All return 0 for a == b, a negative number for a < b and a positive for a > b.

The "n" variants (e.g., strncmp) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).

The "case" variants are case insensitive comparisons - that is "foo" matches with "Foo" and "foO".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.