pointers-memory · intermediate · ~15 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.A haystack string and a needle string (needle may be empty).
Pointer to the first match in haystack, NULL if not found, haystack for an empty needle.
Do not call the standard strstr.
#include <stddef.h>
const char *my_strstr(const char *haystack, const char *needle) {
/* TODO */
return NULL;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.