Character arrays let you store and work with text in C++. They are simple ways to hold words or sentences as a list of letters.
Character arrays in C++
char arrayName[size]; // Example: char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
The size must be enough to hold all characters plus the special '\0' character that marks the end of the text.
The '\0' character is called the null terminator and tells C++ where the text ends.
char word[5] = {'H', 'e', 'l', 'l', 'o'}; // No null terminator, not a proper string
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Proper string with null terminator
char empty[1] = {'\0'}; // Empty string with only null terminator
char greeting[] = "Hi!"; // Size is automatically set to 4 (3 letters + '\0')
This program creates a character array holding "Hello". It prints the word, changes the first letter to 'Y', then prints the new word "Yello". Finally, it prints each letter separately.
#include <iostream> int main() { // Create a character array to hold the word "Hello" char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Print the greeting std::cout << "Greeting: " << greeting << std::endl; // Change the first letter greeting[0] = 'Y'; // Print the changed greeting std::cout << "Changed Greeting: " << greeting << std::endl; // Show each character one by one std::cout << "Characters: "; for (int i = 0; greeting[i] != '\0'; i++) { std::cout << greeting[i] << ' '; } std::cout << std::endl; return 0; }
Time complexity to access or change a character is O(1) because you use the index directly.
Space complexity is fixed by the array size you declare.
Common mistake: forgetting the null terminator '\0' causes unexpected behavior when printing or using string functions.
Use character arrays when you want simple, fixed-size text storage without extra features of std::string.
Character arrays store text as a list of characters ending with a null terminator '\0'.
Always leave space for the null terminator to mark the end of the text.
You can change characters by accessing array positions directly.