basics · intermediate · ~15 min
Walk a pointer through a NUL-terminated string and count the steps.
strlen is the canonical "rewrite a libc function" exercise. It's only one line of real code, but doing it correctly teaches you C's two foundational ideas: pointer arithmetic, and that strings are NUL-terminated.
Implement:
size_t my_strlen(const char *s);
It must return the number of bytes in s BEFORE the terminating '\0'. No use of strlen from the standard library.
size_t my_strlen(const char *s);
A NUL-terminated string.
The number of characters before the '\0', as a size_t. Empty string → 0.
strlen, strnlen, or anything in <string.h> that you didn't write.'\0' — your function would read forever on a malformed string.s is guaranteed non-NULL by the harness, but defensive code returns 0 for NULL anyway.| Input | Returns |
|---|---|
"hello" |
5 |
"" |
0 |
"a" |
1 |
"hello, world" |
12 |
0.'\0').0 (the literal byte, not the character '0'). Loop until you find one.const char *p = s; while (*p) p++; return p - s; — pointer subtraction gives you the count.*p != '\0'. That works, but while (*p) is the same thing because '\0' is zero, which is falsy in C. Both are right; the second is idiomatic.for (int i = 0; s[i] != '\0'; i++) and returning i. Correct, but slower idiomatic style than pointer arithmetic.int instead of size_t. The standard strlen returns size_t.'\0' is the byte 0, not the character '0' (ASCII 48).This is your first taste of:
p - s gives a difference in elements, here in bytes).<string.h> function (strcmp, strcat, strchr) reads exactly the same way.The smallest possible exercise that uses pointers, the string convention, AND pointer arithmetic. Get all three at once.
A pointer to a NUL-terminated string.
size_t — the byte count before the NUL.
No <string.h> calls. Don't read past the NUL.
#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.