pointers-memory · beginner · ~6 min
Measure a string with two pointer positions.
Compute a string's length using pointer subtraction: advance a pointer to the NUL terminator, then subtract the start.
Implement int str_len_ptr(const char *s) that returns the number of characters before the terminating NUL, by walking a pointer to the '\0' and returning the distance travelled. No main — the grader calls it.
s — a NUL-terminated string.
Returns the length as an int (the count of characters before '\0').
str_len_ptr("hello") -> 5
str_len_ptr("") -> 0
Drill: practice one contract before combining it with other skills.
s — a NUL-terminated string.
Returns the length as an int (the count of characters before '\0').
s is non-NULL and NUL-terminated; length fits int. Return character count excluding the terminator. Do not mutate or allocate.
int str_len_ptr(const char *s) {
/* TODO */
return 0;
}
Counting the terminator or returning sizeof a pointer.
Empty string returns zero; one character; whitespace counts; stop at the first embedded NUL.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.