Strings: char arrays and the null terminator
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Text is an array of chars
- C has no separate string type. A string is just an array of
char. char word[] = "hi";actually stores'h','i', and a hidden'\0'at the end.- You can read one character at a time with an index, exactly like any array.
The invisible terminator '\0'
- Every C string ends with a special null terminator, written
'\0'(a byte equal to0). - It marks where the text stops. The word
"hi"takes three bytes:'h','i','\0'. - Functions know a string has ended when they reach
'\0'— there is no stored length.
Walking a string
- To visit each character, loop an index while
s[i] != '\0'. - When
s[i]becomes'\0', you have reached the end — stop. - This is how you count characters, search, or copy a string by hand.
#include <stdio.h>
int main(void) {
char word[] = "hello";
int len = 0;
while (word[len] != '\0') { // stop at the terminator
len++;
}
printf("%d\n", len); // 5
return 0;
}
The <string.h> toolbox
<string.h>has ready-made helpers:strlen(s)(length),strcpy(dst, src)(copy),strcmp(a, b)(compare),strcat(dst, src)(join).strcmp(a, b)returns0when the two strings are equal — handy in tests.- These all rely on the
'\0'terminator to know where each string ends.
Now you try
- To change a string in place, the caller must pass a writable
chararray, not a fixed text. - Stop your loops at
'\0'. Do not write amain— the checker provides one.
Complete int count_char(const char *s, char c) so it returns how many times c appears in the string s. Loop until you reach the end of the string. Do not write a main.
Click Run to see the output here.
Complete int my_strlen(const char *s) so it returns the length of s without calling strlen. Walk the array until you reach the end. Do not write a main.
Click Run to see the output here.
Complete void reverse_str(char *s) so it reverses the characters of s in place. Find the length, then swap from both ends toward the middle. Do not write a main.
Click Run to see the output here.