pointers-memory · intermediate · ~15 min

Flatten pointer-to-pointer jagged array

Navigate pointer-to-pointer arrays and serialize fragmented memory into contiguous buffers.

Challenge

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.

Your Task

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.

Rules

  1. If lines == NULL, out == NULL, or out_cap == 0, return -1.
  2. If count == 0, write "" (NUL byte) to out[0] and return 0.
  3. If any line pointer lines[i] is NULL, return -1.
  4. If the combined length plus delimiters and the final NUL exceeds out_cap, return -1 without overflowing.
  5. On success, ensure out is NUL-terminated and return the number of characters written (excluding NUL).

Example

char *words[] = { "alpha", "beta", "gamma" };
char buf[32];
flatten_strings(words, 3, '/', buf, sizeof buf); // returns 16, buf = "alpha/beta/gamma"

Input format

lines: array of string pointers; count: number of strings; delimiter: separator; out: destination; out_cap: capacity.

Output format

Returns characters written on success, or -1 on overflow/error.

Constraints

C11 freestanding. Never write past out_cap.

Starter code

#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;
}

Common mistakes

Appending delimiter after the last element; forgetting NUL byte; off-by-one capacity verification.

Edge cases to handle

count == 0 returns 0; empty lines (e.g. ""); single line has no delimiter; buffer capacity boundary.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.