Step 1 of 6
The null terminator
You've been printing strings since the first lesson. Now it's time to see what they really are, because C strings behave very differently from strings in most other languages.
C has no string type. A string is just a char array, and the end of the text is marked by a special character with the value 0, written '\0' and called the null terminator.
#include <stdio.h>
int main(void) {
char word[] = "map";
printf("%s\n", word);
printf("%zu bytes\n", sizeof(word));
printf("codes: %d %d %d %d\n", word[0], word[1], word[2], word[3]);
word[0] = 'c';
printf("%s\n", word);
return 0;
}
map
4 bytes
codes: 109 97 112 0
cap
"map" has 3 letters but takes 4 bytes: 'm', 'a', 'p' and '\0'. When you write a string in double quotes, the compiler adds the terminator for you.
Why a terminator?
A plain array doesn't know its own length. Functions like printf("%s", ...) need to know where the text ends, so they print characters one by one until they reach '\0'. Every string function in C relies on this rule.
If the terminator is missing, those functions keep going past the end of the array, printing or copying whatever bytes happen to follow in memory, until they happen to hit a zero. That's a bug, and a common source of crashes and security problems.
Strings are editable arrays
Because a string is a char array, you can change individual characters with an index, as the example does with word[0] = 'c'. When you build a string by hand, character by character, you must put the '\0' at the end yourself.
Your turn: build the string "ak" by hand and print it.