pointers-memory · intermediate · ~15 min
Navigate pointer-to-pointer arrays and serialize fragmented memory into contiguous buffers.
Array of strings char **lines (such as argv or token lists) scatter small allocations across memory. Flattening them into a single contiguous string separated by a delimiter creates a compact, cache-friendly payload.
Implement:
int flatten_strings(char *const *lines, size_t count, char delimiter, char *out, size_t out_cap);
Concatenate count strings from lines into out, separated by delimiter.
lines == NULL, out == NULL, or out_cap == 0, return -1.count == 0, write "" (NUL byte) to out[0] and return 0.lines[i] is NULL, return -1.out_cap, return -1 without overflowing.out is NUL-terminated and return the number of characters written (excluding NUL).char *words[] = { "alpha", "beta", "gamma" };
char buf[32];
flatten_strings(words, 3, '/', buf, sizeof buf); // returns 16, buf = "alpha/beta/gamma"
lines: array of string pointers; count: number of strings; delimiter: separator; out: destination; out_cap: capacity.
Returns characters written on success, or -1 on overflow/error.
C11 freestanding. Never write past out_cap.
#include <stddef.h>
/* Flatten count lines into out separated by delimiter.
Return total characters written (excluding NUL), or -1 on error/overflow. */
int flatten_strings(char *const *lines, size_t count, char delimiter, char *out, size_t out_cap) {
(void)lines; (void)count; (void)delimiter; (void)out; (void)out_cap;
return -1;
}
Appending delimiter after the last element; forgetting NUL byte; off-by-one capacity verification.
count == 0 returns 0; empty lines (e.g. ""); single line has no delimiter; buffer capacity boundary.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.