pointers-memory · intermediate · ~8 min
Return a valid pointer only when the index is in range.
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.
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.
s — a NUL-terminated string. i — a (possibly out-of-range or negative) index.
Returns a pointer to character i of s if in range, otherwise NULL.
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
i equal to the length (one past the end): NULL.i: NULL.Drill: practice one contract before combining it with other skills.
s — a NUL-terminated string. i — a (possibly out-of-range or negative) index.
Returns a pointer to character i of s if in range, otherwise NULL.
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.
#include <string.h>
#include <stddef.h>
const char *char_at(const char *s, int i) {
/* TODO */
return NULL;
}
Forming the pointer before validating the index, or assuming bounds checks establish lifetime.
Negative index; index equal to length; empty string; last valid character.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.