pointers-memory · intermediate · ~15 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.s — a NUL-terminated string; i — an index that may be out of range.
A pointer to character i, or NULL if i is out of range.
In-range means 0 <= i < length(s); otherwise return NULL.
#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.