Strings as Character Arrays
There is no string type in C. There is only a char array with a null byte at the end, and a library that trusts you to keep it there.
In plain English
A C string is a row of letters with a tiny stop sign at the end.
Null-terminated character arrays
A C string is a sequence of characters ending with the null character '\0'. The terminator is not part of the visible text, but it is part of the array. String literals such as "hello" are stored as six characters including the terminator. A char array can hold a string only if it has room for the text plus one.
char greeting[6] = "hello"; /* h e l l o \0 */
printf("%s\n", greeting);
printf("length = %zu\n", strlen(greeting)); /* 5 */sizeof versus strlen
sizeof reports the number of bytes in the array, including the terminator. strlen counts the characters before the terminator. For char s[] = "cat", sizeof(s) is 4 and strlen(s) is 3. A missing terminator turns a string into a buffer overrun waiting to happen, because the string functions keep reading until they find a zero byte.
char s[] = "cat";
printf("%zu\n", sizeof(s)); /* 4 */
printf("%zu\n", strlen(s)); /* 3 */Key takeaways
- A C string is a char array ending in '\0'.
- The visible length is strlen(); storage must include the terminator.
- sizeof includes the terminator; strlen does not.
- A missing terminator causes undefined behaviour.
Common pitfalls
- Forgetting the extra byte for the null terminator.
- Calling strlen on a non-terminated array.
- Confusing sizeof and strlen.
Key focus
- Expect questions on strlen versus sizeof for a char array.
- Trace buffer contents after a string copy.
Quick check
1. How many bytes does char s[] = "cat"; occupy?
2. What does strlen("cat") return?