pointers-memory · beginner · ~6 min

String length by pointer

Measure a string with two pointer positions.

Challenge

Compute a string's length using pointer subtraction: advance a pointer to the NUL terminator, then subtract the start.

Task

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.

Input

s — a NUL-terminated string.

Output

Returns the length as an int (the count of characters before '\0').

Example

str_len_ptr("hello")   ->   5
str_len_ptr("")        ->   0

Edge cases

  • Empty string: returns 0.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

s — a NUL-terminated string.

Output format

Returns the length as an int (the count of characters before '\0').

Constraints

s is non-NULL and NUL-terminated; length fits int. Return character count excluding the terminator. Do not mutate or allocate.

Starter code

int str_len_ptr(const char *s) {
    /* TODO */
    return 0;
}

Common mistakes

Counting the terminator or returning sizeof a pointer.

Edge cases to handle

Empty string returns zero; one character; whitespace counts; stop at the first embedded NUL.

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.