pointers-memory · beginner · ~8 min

Find a character

Return a pointer into a string.

Challenge

Find the first occurrence of a character in a string and return a pointer to it, exactly like the standard strchr.

Task

Implement const char *find_char(const char *s, char c) that returns a pointer to the first c in s, or NULL if c does not appear. The terminating NUL is included in the search. No main — the grader calls it.

Input

s — a NUL-terminated string. c — the character to search for.

Output

Returns a pointer into s at the first match, or NULL if c is absent.

Example

find_char("hello", 'l')   ->   pointer to "llo" (index 2)
find_char("hello", 'h')   ->   pointer to start
find_char("hello", 'z')   ->   NULL

Edge cases

  • Character absent: return NULL.
  • Match at the first position: return s itself.

Why this matters

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

Input format

s — a NUL-terminated string. c — the character to search for.

Output format

Returns a pointer into s at the first match, or NULL if c is absent.

Constraints

s is non-NULL and points to a live NUL-terminated string. Search includes the terminator. Return a borrowed pointer into s or NULL; do not modify or free input.

Starter code

#include <stddef.h>

const char *find_char(const char *s, char c) {
    /* TODO */
    return NULL;
}

Common mistakes

Stopping before checking whether the terminator itself is the requested character.

Edge cases to handle

Empty string; missing character; repeated character returns first match; searching for the zero character returns the terminator.

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