C Strings and the Null Terminator
Store a label and its ending
An integer array needed a separate count. A C string marks its end with a special character stored inside the array:
A character is one value such as 'M', written in single quotes. A string literal such as "Map", written in double quotes, supplies a sequence of characters. In char label[] = "Map";, C creates a modifiable array with four elements: 'M', 'a', 'p', and '\0'.
The final null character has value zero; it is not the printable digit '0' and is not a newline. It tells %s where the string ends. Use %c for one character and %s for the entire terminated string. strlen from <string.h> reports 3 because it does not count \0.
The first print reads up to the terminator; the second reads only element 0:
#include <stdio.h>
int main(void) {
char label[] = "Map";
printf("Label: %s\n", label);
printf("First: %c\n", label[0]);
return 0;
}
label[3] is the null terminator, not a printable fourth letter.
Capacity versus visible length
char name[4] = "Ada"; leaves room for the terminator. char name[3] = "Ada"; does not, so printing that array with %s would be unsafe. Do not run that unsafe case or call strlen on an unterminated array.
Capacity and string length answer different questions. For char name[8] = "Ada";, sizeof name is 8 bytes: the entire array. strlen(name) is 3: the bytes before the first null character. The terminator uses one slot; the remaining four slots are also initialized to zero. These examples use simple single-byte letters, so byte length matches letter count. strlen is not a general count of displayed characters in text encodings such as UTF-8.
This program prints both measurements with %zu, the conversion for size_t:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[8] = "Ada";
printf("Capacity: %zu\n", sizeof name);
printf("Length: %zu\n", strlen(name));
return 0;
}
A char occupies one C byte, so this array's byte size is also its element count. Keep its terminating null character when changing letters.