char array handling guide for beginners

Hi,
because i remember to my own confusion and frustration with char arrays I hope to help some with the following handling exambles.

char  array[12]="asdfgh"; //the max. string length is 11 characters
                          // and Null as string-terminator
void setup() {
Serial.begin(9600);
//String manipulations
Serial.println(array);    //-> asdfgh
Serial.println(array[2]); //-> d
Serial.println(array+2);  //-> dfgh
//but following generate compiler error
//array+=2; //incompatible types in assignment of 'int' to 'char [10]'
strcpy(array,"hallo");
Serial.println(array);    //-> hallo
strcpy(array,"");
Serial.println(array);    //->
strcpy(array,"23456789");
Serial.println(array);    //-> 23456789
strncpy(array,"hallo",2); //!!!see 2 lines later
Serial.println(array);    //-> ha456789
array[2] = '\0';  //terminator neccessary
Serial.println(array);    //-> ha
strcat(array,"567");
Serial.println(array);    //-> ha567
strncat(array,array,3);
Serial.println(array);    //-> ha567ha5
strcpy(array,array+3);
Serial.println(array);    //-> 67ha5

//add bytewise inputs to char array
Serial.println("");
Serial.println("Bytewise add:");
byte  InputChar='a';
uint8_t   InputInt=108; //108 ist the char 'l'
int   i;
strcpy(array,"test");
Serial.println(array);    //-> test
i=strlen(array);
array[i++]=InputChar; // put InputChar at location i & increment i
array[i]='\0';  // allways terminate strings
Serial.println(array);    //-> testa

array[i++]=InputInt;  //this overwrites last written terminator
array[i]='\0';  //new string terminator
Serial.println(array);    //-> testal
}

void loop() {}
1 Like

Small note:

byte  InputChar='a';
uint8_t   InputInt=108; //108 ist the char 'l'

The first isn't a char and the second not an int...

char  InputChar='a';
byte  InputByte=108; //108 is the char 'l', but try not to do this ;)