Course contentsShow
← C
Lesson 419 of 1,2196. Arrays and StringsFree lesson

Initializing strings with sizes

Initializing strings with sizes

What you'll learn: How to declare a string with a specific size and why the "null terminator" requires you to always add one extra slot.

The "Room for the Door" Rule

In C, a string is just an array of characters. When you initialize a string with a specific size, like char name[10], you are essentially building a row of lockers. However, there is a catch: C strings must always end with a special hidden character called the null terminator, written as \0.

Think of this like a train. If you want a train to carry five passenger cars, you actually need a sixth "caboose" at the very end to signal to the station that the train is over. If you don't leave room for that caboose, the train keeps "running" into other parts of your computer's memory, causing bugs and crashes.

Sizing it Right

When you define the size of your array, you must ensure the size is at least length + 1. If you want to store the word "Apple," which has 5 letters, your array size must be at least 6.

#include <stdio.h>

int main() {
    // "C-Style" has 7 letters. We need 8 slots.
    char category[8] = "C-Style"; 

    // If we have extra space, that's fine! 
    // The rest of the slots just stay empty.
    char name[20] = "Alice";

    printf("Category: %s\n", category);
    printf("Name: %s\n", name);

    return 0;
}

What happens if you forget?

If you try to cram a 5-letter word into a char[5] array, there is no room left for the \0 terminator. C won't always complain immediately, but when you try to print that string, the computer will start at the first letter and keep reading past the end of your array, printing random garbage memory until it happens to stumble upon a zero somewhere else.

By explicitly setting a size larger than your text (like char buffer[100]), you create a "safety zone." You can put a short word in a big box, but you can never put a big word in a small box.

Key takeaway

Always size your character arrays to be at least one character longer than the text they will hold to account for the null terminator (\0).