Strings are arrays with a finish line
Work safely with null-terminated character arrays, input, comparison, length, and arrays of strings.
After this lesson
You should be able to
- Explain the role of the terminating null character.
- Use bounded input and standard string functions with adequate storage.
The invisible final byte
A C string is a char array whose meaningful characters end with '\0'. The literal "CSE" needs four bytes: C, S, E, and the terminator. Functions such as strlen search for that terminator, so a missing one can make them read beyond the array.
An array name is not a string value that can be assigned with = after declaration. Use initialization, bounded copying, or formatted output into the destination. Always reserve space for the terminator.
char name[40];
if (fgets(name, sizeof name, stdin) != NULL) {
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s\n", name);
}Compare content, not addresses
strcmp compares string content lexicographically and returns zero when equal. Writing a == b compares pointer or array-decayed addresses, not the characters. strlen counts characters before the terminator; sizeof an in-scope array reports its storage bytes.
An array of strings may be a two-dimensional char array with fixed capacity per row, or an array of pointers to string literals. These models have different ownership and modification rules.
Try it yourself
Given char word[] = "code";, predict strlen(word) and sizeof word.
Need a hint?
One result excludes the null terminator; the other includes its storage.
Check the worked solution
strlen(word) is 4 and sizeof word is 5.
Quick check
How should two C string contents be tested for equality?
Why this lesson exists
Syllabus mapping
Strings · Character arrays · String functions · Arrays of strings
Maps to course outcomes CO3, CO5.