pointers-memory · intermediate · ~8 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.

Why this matters

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

Input format

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

Output format

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

Constraints

s is non-NULL and points to a live terminated string whose length fits int. Return a borrowed pointer only for 0 <= i < length; otherwise NULL. The caller must keep s alive.

Starter code

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

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

Common mistakes

Forming the pointer before validating the index, or assuming bounds checks establish lifetime.

Edge cases to handle

Negative index; index equal to length; empty string; last valid character.

Up next

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