Lesson 4 of 23
wc -c
wc -c: Count Characters
wc (word count) counts lines, words, and characters in a file. With -c it counts bytes (characters):
$ echo "Hello" | wc -c
6
Six because "Hello" is 5 characters plus the newline echo appends.
Your Implementation
Write int count_chars(const char *s) that returns the total number of characters in the string, including newlines.
int count_chars(const char *s) {
int n = 0;
while (*s++) n++;
return n;
}
This is essentially strlen — walk the string until the null terminator, counting each step.
The Null Terminator
C strings end with a '\0' byte. The pointer arithmetic while (*s++) works because:
*sdereferences the pointer to get the current characters++advances the pointer (but evaluates before incrementing, so we read the character first)- When
*sis'\0'(zero / false), the loop ends
Your Task
Implement count_chars that returns the number of characters in the string.
TCC compiler loading...
Loading...
Click "Run" to execute your code.