basics · intermediate · ~15 min

Find a flag's value

Look up an option's value in argv.

Challenge

Look up the value that follows a command-line option, like reading -o out.txt.

Task

Implement const char *flag_value(int argc, char **argv, const char *flag) that finds flag in argv (searching from index 1) and returns the argument immediately after it. Return NULL if flag is not present, or if it appears as the very last argument (so there is no value after it). No main — the grader calls it.

Input

int argc, char **argv, and the flag string flag to look up.

Output

Returns a pointer to the argument following flag, or NULL if absent or dangling.

Example

argv = {"prog","-o","out.txt","-v"}
flag_value(4, argv, "-o")   ->   "out.txt"
flag_value(4, argv, "-x")   ->   NULL        (flag absent)
flag_value(4, argv, "-v")   ->   NULL        (no value after it)

Edge cases

  • A flag in the last position has no following value, so return NULL.

Rules

  • Guard the i+1 lookup so a trailing flag returns NULL instead of reading past argv.

Input format

int argc, char **argv, and the flag string to look up.

Output format

The argument after flag, or NULL if absent or dangling.

Constraints

Search from index 1; return NULL if flag is last or missing.

Starter code

#include <string.h>
#include <stddef.h>

const char *flag_value(int argc, char **argv, const char *flag) {
    /* TODO */
    return NULL;
}

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