Codiqo

Learn C · lesson 29 of 60 · about 8 minutes

Characters and the Null Terminator

Count the letters in the user's name and cut it short for the log: see how C stores text as an array of characters ending in a zero.

What you'll learn

  • Declare a string as a char array
  • Explain the '\0' terminator
  • Loop over a string's characters

The user's name

Since chapter 1 the report has read the user's name into char user[20] and printed it with %s. Now it needs to work with the letters: how long is the name, and what's a short version of it, at most 8 letters, for the log? There's no length stored anywhere. The name ends where its '\0' is, so the report walks along it until it gets there, and the short copy needs a '\0' of its own.

Text is just chars in a row

C has no separate string type. A string is a char array whose last character is '\0': a zero byte that marks where the text ends.

char name[] = "Phoebe"; makes an array of 7 chars: P, h, o, e, b, e and '\0'. The compiler adds the terminator for you.

Peeking inside a string

#include <stdio.h>

int main(void) {
    char name[] = "Phoebe";
    printf("%s has %zu bytes\n", name, sizeof(name));
    printf("First letter: %c\n", name[0]);
    printf("Terminator value: %d\n", name[6]);
    name[0] = 'D';
    printf("%s\n", name);
    return 0;
}

Output

Phoebe has 7 bytes
First letter: P
Terminator value: 0
Dhoebe

Walking a string

Because every string ends in '\0', you can loop until you reach it, without knowing the length in advance. That's exactly how printf's %s knows when to stop.

Step through the loop

#include <stdio.h>

int main(void) {
    char word[] = "box";
    int len = 0;
    while (word[len] != '\0') {
        len++;
    }
    printf("%d\n", len);
    return 0;
}

Output

3

Making a string yourself

When you copy letters into an array one at a time, nothing adds the '\0' for you. Copy the letters, then put a '\0' straight after the last one, and make the array one byte bigger than the longest text it has to hold.

The first 3 letters

#include <stdio.h>

int main(void) {
    char word[] = "penguin";
    char start[4];
    for (int i = 0; i < 3; i++) {
        start[i] = word[i];
    }
    start[3] = '\0';
    printf("%s\n", start);
    return 0;
}

Output

pen

Tip

'\0' is the zero character, not the digit '0'. '0' has the value 48; '\0' has the value 0.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.