basics · intermediate · ~15 min
Look up an option's value in argv.
Look up the value that follows a command-line option, like reading -o out.txt.
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.
int argc, char **argv, and the flag string flag to look up.
Returns a pointer to the argument following flag, or NULL if absent or dangling.
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)
NULL.i+1 lookup so a trailing flag returns NULL instead of reading past argv.int argc, char **argv, and the flag string to look up.
The argument after flag, or NULL if absent or dangling.
Search from index 1; return NULL if flag is last or missing.
#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.