pointers-memory · intermediate · ~15 min
Practise pointer assignment with the canonical idiom `while ((*d++ = *s++));`
Implement char *my_strcpy(char *dst, const char *src) copying the null terminator too, and returning dst. Do not call the standard strcpy.
Writing your own strcpy gives a visceral understanding of why the function is unsafe by default — there's no destination size argument, just a faith-based copy.
char *my_strcpy(char *dst, const char *src) {
/* TODO */
return dst;
}
Forgetting to copy the trailing NUL (now dst isn't a valid C string). Mutating the source. Returning the wrong pointer (strcpy returns dst).
Empty source ("") — still copies the NUL. Source equals destination — undefined (use memmove).
O(strlen(src)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.