0
0
AutocadHow-ToBeginner · 4 min read

How to Use Char Array in Arduino: Syntax and Examples

In Arduino, a char array is used to store a sequence of characters, like a word or sentence. You declare it with char name[size] and can initialize it with characters or a string literal. Char arrays are useful for handling text data in your Arduino programs.
📐

Syntax

To use a char array in Arduino, you declare it by specifying the type char, the array name, and its size in square brackets. You can initialize it with characters or a string literal enclosed in double quotes. Remember to leave space for the null character \0 that marks the end of the string.

  • char: data type for characters
  • name[size]: array name and size
  • Initialization: optional, with characters or string
arduino
char myArray[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char myString[6] = "Hello";
💻

Example

This example shows how to declare a char array, initialize it with a string, and print it to the Serial Monitor. It demonstrates storing and displaying text using a char array.

arduino
void setup() {
  Serial.begin(9600);
  char greeting[15] = "Hello, Arduino";
  Serial.println(greeting);
}

void loop() {
  // Nothing here
}
Output
Hello, Arduino
⚠️

Common Pitfalls

Common mistakes when using char arrays include:

  • Not leaving space for the null terminator \0, which ends the string.
  • Initializing a char array with a string literal without enough size, causing overflow.
  • Modifying string literals directly, which is not allowed.

Always ensure your array size is at least one more than the string length to hold the null character.

arduino
/* Wrong: no space for null terminator */
char wrongArray[5] = "Hello"; // "Hello" needs 6 chars including \0

/* Right: space for null terminator */
char rightArray[6] = "Hello";
📊

Quick Reference

ConceptDescriptionExample
DeclarationCreate a char array with fixed sizechar name[10];
InitializationSet values at declarationchar name[6] = "Hello";
Null TerminatorMarks end of string, must fit in arraychar name[6] = "Hello"; // includes '\0'
PrintingUse Serial.println() to displaySerial.println(name);
ModificationChange characters by indexname[0] = 'h';

Key Takeaways

Always allocate enough space for the null terminator '\0' in char arrays.
Initialize char arrays with string literals using double quotes and proper size.
Use Serial.println() to print char arrays as strings on Arduino.
Avoid modifying string literals directly; use char arrays instead.
Access and change individual characters by their index in the array.