Declaring arrays of type char
What you'll learn: How to create a container in memory that stores a sequence of individual characters.
In C, we have a specific data type for single letters, numbers, or symbols: the char. However, most real-world data—like names, messages, or addresses—consists of many characters joined together. To handle this, we use a character array.
The character egg carton
Think of a standard int array like a row of large boxes, each holding a big number. A char array is more like an egg carton. Each individual slot is small, designed to hold exactly one character (like 'A', '7', or '$'). When you declare a character array, you are telling the computer, "Reserve a row of these small slots for me and give the whole row one name."
How to declare them
To declare a character array, you state the data type (char), the name of your variable, and the number of slots you need inside square brackets.
// Reserving space for 10 individual characters
char username[10];
// Reserving space and giving it initial values
char greeting[5] = {'H', 'e', 'l', 'l', 'o'};
In the first example, username is a container that can hold 10 characters. Right now, it is full of "garbage" data—whatever happened to be in memory at that moment. In the second example, we immediately filled the five slots with the letters of the word "Hello."
Why size matters
When you declare char message[20], the computer sets aside exactly 20 bytes of memory. Unlike a modern word processor, C won't automatically expand this "carton" if you try to stuff more letters into it later. If you try to put 25 characters into a 20-slot array, you’ll end up "overwriting" other data nearby, which usually causes your program to crash or behave erratically.
Always ensure your array size is large enough to hold the maximum amount of data you expect. It is perfectly fine to have empty slots at the end of your array, but it is dangerous to have too few.
Key takeaway
A char array is a fixed-size sequence of memory slots where each slot holds exactly one character.