pointers-memory · beginner · ~15 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. 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.

Input format

s — a NUL-terminated string; c — the character to find.

Output format

A pointer to the first occurrence, or NULL if absent.

Starter code

#include <stddef.h>

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

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