A string ends at the null terminator
A C string is a char array with a '\0' (the null terminator) after the last letter. "cat" takes four boxes.
my_strlen moves the pointer p one box at a time. Watch its arrow slide along word until it lands on '\0', then the length is how far it moved.
#include <stdio.h>
int my_strlen(const char *s) {
const char *p = s;
while (*p != '\0') {
p++;
}
return (int)(p - s);
}
int main(void) {
char word[] = "cat";
int len = my_strlen(word);
printf("%s has %d letters\n", word, len);
return 0;
}
Output:
cat has 3 letters
From the lesson: Strings