pointers-memory · intermediate · ~20 min
Nested pointer iteration; corner cases of empty inputs.
Write your own strstr: find the first place one string appears inside another.
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.
haystack: the NUL-terminated string to search in.needle: the NUL-terminated substring to find (may be empty).A pointer into haystack at the start of the first match, or NULL if needle is not found. An empty needle returns haystack itself.
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
haystack.NULL.strstr.Transfer exercise: apply the lesson to a complete function contract.
haystack: the NUL-terminated string to search in.needle: the NUL-terminated substring to find (may be empty).A pointer into haystack at the start of the first match, or NULL if needle is not found. An empty needle returns haystack itself.
Both strings are non-NULL, live, and terminated. Return a borrowed first-match pointer or NULL; do not modify either string or call strstr.
#include <stddef.h>
const char *my_strstr(const char *haystack, const char *needle) {
/* TODO */
return NULL;
}
Stopping after a partial match or skipping overlapping candidate starts.
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.