pointers-memory · intermediate · ~20 min

Implement strstr

Nested pointer iteration; corner cases of empty inputs.

Challenge

Write your own strstr: find the first place one string appears inside another.

Task

Implement const char *my_strstr(const char *haystack, const char *needle) that returns a pointer to the first occurrence of needle within haystack, or NULL if it does not appear. No main — the grader calls it.

Input

  • haystack: the NUL-terminated string to search in.
  • needle: the NUL-terminated substring to find (may be empty).

Output

A pointer into haystack at the start of the first match, or NULL if needle is not found. An empty needle returns haystack itself.

Example

my_strstr("hello world", "world")   ->   pointer to "world" (haystack+6)
my_strstr("hello world", "hello")   ->   haystack
my_strstr("hello world", "xyz")     ->   NULL
my_strstr("hello", "")              ->   haystack

Edge cases

  • Empty needle returns haystack.
  • No match returns NULL.

Rules

  • Do not call the standard strstr.

Why this matters

Transfer exercise: apply the lesson to a complete function contract.

Input format

  • haystack: the NUL-terminated string to search in.
  • needle: the NUL-terminated substring to find (may be empty).

Output format

A pointer into haystack at the start of the first match, or NULL if needle is not found. An empty needle returns haystack itself.

Constraints

Both strings are non-NULL, live, and terminated. Return a borrowed first-match pointer or NULL; do not modify either string or call strstr.

Starter code

#include <stddef.h>

const char *my_strstr(const char *haystack, const char *needle) {
    /* TODO */
    return NULL;
}

Common mistakes

Stopping after a partial match or skipping overlapping candidate starts.

Edge cases to handle

Empty needle returns haystack; longer needle; partial-prefix mismatch; repeated candidate starts.

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