Lesson 65 +10 XP

Strings

Strings

A string is a sequence of characters. In C, a string is really an array of characters ending with a null character.

Strings are char arrays

char greetings[] = "Hello World!";

Behind the scenes it's an array of chars:

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', ... , '\0'};

The null terminator

Every C string ends with \0, a special character (code 0) that marks the end of the string. It is added automatically to string literals.

Printing a string

printf("%s", greetings);

The %s specifier prints characters until it hits the \0.

Accessing characters

printf("%c\n", greetings[0]);   // H

Careful with size

"Hello" takes 5 visible characters plus the \0, so the array holds 6 slots:

char word[6] = "Hello";

If you don't, overflow.

TL;DR

  • A C string is a char array ending in \0.
  • Print it with %s.
  • Access single characters with indexes.
  • Always account for the null terminator's space.