1

I've following code:

char a[5] = "bang";
char b[5] = "";
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (a != b){
  for(int i=0; i<4; i++){
      b[i] = a[i];
    }
    Serial.print("b: ");
    Serial.println(b);
    Serial.println("Not Equal");
    delay(1000);
  }
  else{
    delay(1000);
  }

}

Why the output is:

b: bang
Not Equal
b: bang
Not Equal 
b: bang
Not Equal

Shouldn't a and b equal after first loop?

  • Try if(strcmp(a, b) != 0) instead of if (a != b) – Matej Feb 21 at 7:24
1

As Matej already mentioned, use:

strcmp(a, b) != 0

If you compare a and b, what you are actually doing is comparing two pointers (to the text characters). These pointers a and b are stored at different locations in memory, although the content itself can be the same.

See it as this:

a   memory location 0x12345: "Bang"
b   memory location 0x1234A: "Bang"    (5 memory locations further)
0

Two errors. One is already commented by @michel-keijzers about the strcmp() to compare to strings in different memory position.

The another error: C-strings are null-terminated so, you must copy the 5th character too or, as in your code, string is not being determined its length:

for(int i = 0; i < 5; i++) {
  b[i] = a[i];
}

... or better, use strcpy():

strcpy(b, a);
  • strncpy was not ment for this, it had a specific use in the past (long long time ago), see for example: stackoverflow.com/questions/6987217/… The sooner your forget about strncpy, the better. – Jot Feb 21 at 9:58
  • Well, IMHO, strncpy usage is a best practice in order to avoid memory overrides. Anyway, I edit the answer with strcpy to avoid parallel discusion. – caligari Feb 21 at 10:06

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