pointers-memory · intermediate · ~15 min

Bounds-checked element pointer

Return a valid pointer only when the index is in range.

Challenge

Return a pointer to a string's i-th character only when the index is in range, so a caller can never form a pointer that would read out of bounds.

Task

Implement const char *char_at(const char *s, int i) that returns &s[i] when 0 <= i < length(s), otherwise NULL. No main — the grader calls it.

Input

s — a NUL-terminated string. i — a (possibly out-of-range or negative) index.

Output

Returns a pointer to character i of s if in range, otherwise NULL.

Example

char_at("abc", 0)    ->   pointer to 'a'
char_at("abc", 2)    ->   pointer to 'c'
char_at("abc", 3)    ->   NULL   (past the end)
char_at("abc", -1)   ->   NULL

Edge cases

  • i equal to the length (one past the end): NULL.
  • Negative i: NULL.

Input format

s — a NUL-terminated string; i — an index that may be out of range.

Output format

A pointer to character i, or NULL if i is out of range.

Constraints

In-range means 0 <= i < length(s); otherwise return NULL.

Starter code

#include <string.h>
#include <stddef.h>

const char *char_at(const char *s, int i) {
    /* TODO */
    return NULL;
}

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