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
| Concept | Description | Example |
|---|---|---|
| Declaration | Create a char array with fixed size | char name[10]; |
| Initialization | Set values at declaration | char name[6] = "Hello"; |
| Null Terminator | Marks end of string, must fit in array | char name[6] = "Hello"; // includes '\0' |
| Printing | Use Serial.println() to display | Serial.println(name); |
| Modification | Change characters by index | name[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.