pointers-memory · beginner · ~15 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.

Input format

s — a NUL-terminated string.

Output format

The string length as an int.

Constraints

Measure with pointer subtraction (walk to the NUL, then subtract).

Starter code

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

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