basics · intermediate · ~15 min
Walk a pointer through a NUL-terminated string and count the steps.
Write your own strlen: count the bytes in a C string up to (not including) the NUL terminator.
Implement size_t my_strlen(const char *s) returning the length of the NUL-terminated string s, excluding the terminator. No main — the grader calls it.
A NUL-terminated string s (may be empty).
The number of bytes before the terminating \0, as a size_t.
my_strlen("") -> 0
my_strlen("a") -> 1
my_strlen("hello") -> 5
0.strlen (or any <string.h> length helper).The smallest possible exercise that uses pointers, the string convention, AND pointer arithmetic. Get all three at once.
A NUL-terminated string s.
The byte count before the NUL, as a size_t.
Do not call the standard strlen.
#include <stddef.h>
size_t my_strlen(const char *s) {
/* TODO */
return 0;
}
Returning int instead of size_t. Using s[i] index notation when pointer arithmetic is the idiom. Reading past the NUL.
Empty string → 0. Embedded NUL → terminates at the first one. Very long strings → linear scan, fine.
O(n) where n is the string length. Cannot be faster in the general case — you must touch each byte.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.