A report needs labels as well as numbers: a topic name, a heading. In C, text is not a special type. It is an array of char, and the previous lesson showed that an array does not know its own length. Passing a separate count with every piece of text would be tiresome, so C uses a different convention: the text ends with a zero character, written '\0'. Every function that reads text walks forward until it finds that zero. When the zero is there, this is simple and efficient. When it is missing, or when the array is too small to hold it, reading runs off the end of the array, which is undefined behavior.
Predict and run
Predict all three lines, including both numbers on the second.
#include <stdio.h>
#include <string.h>
int main(void) {
char topic[] = "Code";
printf("%s\n", topic);
printf("%zu %zu\n", strlen(topic), sizeof topic);
topic[0] = 'M';
printf("%s\n", topic);
return 0;
}Check your prediction
Code
4 5
Mode"Code" has four visible characters, but the array holds five: C, o, d, e and the terminator. strlen counts the characters before the terminator, so it says 4. sizeof measures the whole array in bytes, and a char is always exactly one byte, so it says 5. Changing topic[0] replaced one element; the terminator stayed where it was, so the text still ended in the right place.
A string is an array plus a promise
A C string is a sequence of characters followed by '\0'. A string literal such as "Code" always includes that terminator, so char topic[] = "Code"; sizes the array to 5 automatically. %s in printf and strlen from <string.h> both read until the terminator; neither knows the array's size. That gives two rules for every text buffer:
- Reserve one extra element for the terminator. Five visible characters need six elements.
- Make sure the terminator is still inside the array after every change.
C will not enforce either rule. This declaration is legal, and the compiler accepts it without a warning:
char topic[4] = "Code";
printf("%s\n", topic);There is exactly room for the four letters, so C silently drops the terminator. The array is now just four characters, not a string, and printf keeps reading past topic[3] looking for a zero. Whatever it prints, it is undefined behavior. Leave the size out and let the compiler count, or count the terminator yourself.
Walk a string yourself
strlen is not magic. It is a loop that stops at the terminator, and you can write the same loop. It works for any text, because it never needs to know the array size:
#include <stdio.h>
int length(const char text[]) {
int n = 0;
while (text[n] != '\0') {
n++;
}
return n;
}
int main(void) {
printf("%d %d\n", length("focus"), length(""));
return 0;
}5 0The empty string "" is a valid string: an array whose only element is the terminator, so its length is 0.
Comparing and copying need functions
Arrays cannot be assigned with =, and == does not compare their contents. Comparing two strings with == compares where they are stored, not what they say, which is almost never what you want. Use strcmp(a, b) from <string.h>, which returns 0 when the two strings are equal.
To copy text into a buffer, the classic function strcpy copies until the terminator with no idea how big the destination is, so a long source overflows it. A bounded choice that is always safe is snprintf(dest, sizeof dest, "%s", source). It never writes more than sizeof dest bytes, always adds a terminator, and cuts the text short if it does not fit.
#include <stdio.h>
#include <string.h>
int main(void) {
char label[6];
int wanted = snprintf(label, sizeof label, "%s", "Pointers");
printf("%s %zu of %d\n", label, strlen(label), wanted);
printf("%d\n", strcmp(label, "Point") == 0);
return 0;
}Point 5 of 8
1Only five letters fit, because the sixth element is kept for the terminator. snprintf returns the length the full text would have had, 8, so comparing that with the buffer size tells you whether anything was cut. The text was shortened, but the buffer was never overrun, and the result is still a valid string.
Practice
Your turn
Write int count_char(const char text[], char target) that returns how many times target appears in text, walking the string until the terminator. Use it on "banana bread" for 'a' and on the empty string. Also print the text's length from your own loop next to strlen:
Length: 12 (strlen 12)
a: 4
Empty: 0#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "banana bread";
// Write your solution here.
return 0;
}Hint 1: the idea
The loop condition is the terminator check, text[i] != '\0', not an array size. Inside the loop, compare each character with target and count matches.
Hint 2: a first step
Write the length loop first, as in the lesson, and print it next to strlen(text) with %d and %zu. When both say 12, copy the loop into count_char and add the comparison.
Show one solution
#include <stdio.h>
#include <string.h>
int length(const char text[]) {
int n = 0;
while (text[n] != '\0') {
n++;
}
return n;
}
int count_char(const char text[], char target) {
int found = 0;
for (int i = 0; text[i] != '\0'; i++) {
if (text[i] == target) {
found++;
}
}
return found;
}
int main(void) {
char text[] = "banana bread";
printf("Length: %d (strlen %zu)\n", length(text), strlen(text));
printf("a: %d\n", count_char(text, 'a'));
printf("Empty: %d\n", count_char("", 'a'));
return 0;
}Length: 12 (strlen 12)
a: 4
Empty: 0Both functions stop at the terminator, so they work for text of any length without being told a count, and the space between the words is just another character. The empty string stops the loop before the first comparison. In the checkpoint you will go back to arrays of numbers and summarize a whole collection, including an empty one.
Completion is saved in this browser only. It does not measure mastery.