Loading lessons...
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
C
char greetings[] = "Hello World!";Behind the scenes it's an array of chars:
C
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
C
printf("%s", greetings);The %s specifier prints characters until it hits the \0.
Accessing characters
C
printf("%c\n", greetings[0]); // HCareful with size
"Hello" takes 5 visible characters plus the \0, so the array holds 6 slots:
C
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.