linux-sysprog · intermediate · ~15 min

Echo argv with indices

Understand argc/argv layout (without depending on the runtime to inject it).

Challenge

Format command-line arguments into a buffer, each prefixed with its index.

Task

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.

Input

  • 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.

Output

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.

Example

argv = {"prog","alpha","beta"}, argc=3
  ->   out = "0: prog\n1: alpha\n2: beta\n"
argv = {"only"}, argc=1
  ->   out = "0: only\n"

Edge cases

  • argc = 0: out becomes the empty string "".

Rules

  • Use bounded formatting (e.g. snprintf with a running offset); never write past out_sz.

Input format

argc, argv (the argument array), and a writable buffer out of out_sz bytes.

Output format

0 on success (-1 if buffer too small); out holds one "i: \n" line per argument.

Constraints

Bounded formatting only; never write past out_sz; argc may be 0.

Starter code

#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.