pointers-memory · intermediate · ~15 min
Practise pointer assignment with the canonical idiom `while ((*d++ = *s++));`
Write your own strcpy: copy a C string, including its NUL terminator, into a destination buffer.
Implement char *my_strcpy(char *dst, const char *src) that copies src (including the terminating \0) into dst and returns dst. No main — the grader calls it.
dst: a writable buffer large enough to hold src plus its terminator.src: a NUL-terminated source string (may be empty).Returns dst. After the call dst contains a byte-for-byte copy of src including the NUL.
my_strcpy(buf, "hello") -> buf = "hello", returns buf
my_strcpy(buf, "") -> buf = ""
dst.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.
A writable buffer dst and a NUL-terminated source src.
dst (the original pointer); dst now holds a copy of src including the NUL.
Do not call the standard strcpy; dst must be large enough.
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.