Skip to content
FollowtheDamnCode

Strings

Text is an array of characters ending in \0.

5 minute read

Big idea

C has no special "text" type. A string is an array of chars that ends with a hidden null character, '\0', marking where the text stops.

The idea

char name[] = "Maya";

That's five characters, not four:

Index01234
Value'M''a''y''a''\0'

The double quotes add the '\0' for you. Every string function — printf("%s"), strlen, and the rest — reads characters until it hits that '\0'.

  • 'M' in single quotes is one char.
  • "M" in double quotes is a string: 'M' followed by '\0'.

Watch it

Walking a string

Because a string ends at '\0', you loop until you reach it — no length needed:

Count the vowels — change the text
#include <stdio.h>

int main(void) {
    char text[] = "programming in c";
    int vowels = 0;
    for (int i = 0; text[i] != '\0'; i++) {
        char c = text[i];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            vowels++;
        }
    }
    printf("%d vowels\n", vowels);
    return 0;
}
output
4 vowels

Run and edit it in the app.

Watch the loop stop

Characters are numbers

Every char is stored as a small number — its ASCII code. 'A' is 65, 'a' is 97, '0' is 48. That's why c - 'a' gives a letter's position in the alphabet, and c - 32 turns a lowercase letter into uppercase:

Predict: char arithmetic
#include <stdio.h>

int main(void) {
    char c = 'c';
    printf("%d\n", c);
    printf("%d\n", c - 'a');
    printf("%c\n", c - 32);
    return 0;
}
What does it print? Show the answer
99
2
C

Run and edit it in the app.

Common mistake

Making the array too small. char word[4] = "Maya"; has no room for the '\0', so printf keeps reading past the end. Always leave room for one extra character.

Think of it like

A string of beads with a knot at the end. You read the beads until you reach the knot — the knot is how you know the necklace is over.

🕷️ Spidey-sense: A web line is only useful if it's anchored. '\0' is the anchor at the end of every string — cut it and the whole thing goes flying.

Key terms

  • String — A char array ending in '\0'.
  • Null terminator — '\0', the character with code 0 that marks the end.
  • ASCII — The number code for each character, e.g. 'A' = 65.
  • %s — The printf code for a string.

Check yourself

How many chars does "hi" take in memory?

What marks the end of a C string?

What's the difference between 'A' and "A"?