linux-sysprog · intermediate · ~15 min
Understand argc/argv layout (without depending on the runtime to inject it).
Format command-line arguments into a buffer, each prefixed with its index.
Implement int echo_args(int argc, char **argv, char *out, size_t out_sz) that writes one line per argument into out, each in the form i: <arg>\n where i is the 0-based index. No main — the grader passes a fixed argv to simulate a command line.
argc: number of arguments (may be 0).argv: array of argc NUL-terminated argument strings.out / out_sz: a writable buffer and its size in bytes.Returns 0 on success (-1 if the buffer is too small). After the call out is a NUL-terminated string with one i: <arg>\n line per argument.
argv = {"prog","alpha","beta"}, argc=3
-> out = "0: prog\n1: alpha\n2: beta\n"
argv = {"only"}, argc=1
-> out = "0: only\n"
argc = 0: out becomes the empty string "".snprintf with a running offset); never write past out_sz.argc, argv (the argument array), and a writable buffer out of out_sz bytes.
0 on success (-1 if buffer too small); out holds one "i:
Bounded formatting only; never write past out_sz; argc may be 0.
#include <stdio.h>
#include <string.h>
#include <stddef.h>
int echo_args(int argc, char **argv, char *out, size_t out_sz) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.