pointers-memory · intermediate · ~15 min
Bound a copy by the destination capacity.
Copy ints into a destination buffer without ever overrunning it: copy at most as many as the destination can hold, and report how many you actually copied.
Implement int safe_copy_n(int *dst, int dstcap, const int *src, int n) that copies min(n, dstcap) ints from src to dst and returns that count. No main — the grader calls it.
dst — destination buffer. dstcap — its capacity in ints. src — source buffer. n — how many the caller wants to copy.
Returns the number of ints actually copied (min(n, dstcap)); dst is never written past dstcap.
src = {1,2,3,4}, dst capacity 2: safe_copy_n(dst, 2, src, 4) -> 2, dst == {1, 2}
src = {1,2,3,4}, dst capacity 8: safe_copy_n(dst, 8, src, 4) -> 4, dst[0..3] == {1,2,3,4}
n > dstcap: copy only dstcap ints.n <= dstcap: copy all n.dst/dstcap — destination and its capacity; src/n — source and requested count.
The number of ints copied (min(n, dstcap)); dst is never overrun.
Never write past dstcap ints into dst.
int safe_copy_n(int *dst, int dstcap, const int *src, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.