Weird output

I have this code:

if (keypressed == '#') {
      for(unsigned int a = 0; a < sizeof(keys); a = a+1) {
        Serial.print(keys[a]);
      }
    }

Output is this after typing in '147#':

147#147#⸮⸮R⸮tt^⸮3[⸮""""aaaaa

I understand everything up until after the second # symbol. What is this jiberish?

When the hash (#) is pressed, write a null character ('\0') to the next position in the keys[] array. Then you can print it as...

Serial.print(keys);  //print the characters in keys[] up to the null

What MorgnS said.

      for(unsigned int a = 0; a < sizeof(keys); a = a+1) {
        Serial.print(keys[a]);
      }

Tis prints every element of the buffer, including the characters you have not filled in yet.

So when I go to compare then, what is the best way to do this? I am trying here to convert the char array to a string:

String code = "12345";
char keys[5];
.....
String str(keys);
      
      if(keys == code) {
        Serial.print("Access granted");
      }

There is no need to use the (possibly dangerous) String class (capital S). And why do you try to convert it?

String code = "12345";
char keys[5];
.....
String str(keys);

The question is what ..... is; you were told not to post snippets :wink: And I'm not going to dig for other threads :wink: As it stands now, keys is not initialised and next you try to make a string of an uninitialised variable; recipe for disaster.

When you press the # key, add the null terminator to that character array. Next you can use the C-string functions like strlen() and strcmp() and ...

For the code in reply #4, if the character array is null terminated

if (strcmp(keys, "12345") == 0)
{
  // match
}

For the code in the opening post, if the character array is null terminated

      for(unsigned int a = 0; a < strlen(keys); a = a+1)
      {
        Serial.print(keys[a]);
      }

Or indeed a simple Serial.println(keys).

Delta_G:
No, stay away from the String class on a microcontroller. Stick with keeping the strings of characters in char arrays.

May I ask why? Does it take too much memory?
Also, how is it dangerous?

char keys[5];

That's one mistake. You can't fit five characters and a null terminator in an array of five characters.

OOPS, missed that one :wink: