Command-line arguments let one executable receive different startup settings without changing its source. The entry point can be written as int main(int argc, char **argv): argc is the argument count and argv is the table of argument strings. For now, treat argv as an indexable string sequence; pointer mechanics come later.
argc and argv
argv[0] normally stores the name used to launch the program, and the first user-supplied argument is argv[1]. Check argc before accessing any index. Arguments do not automatically become numbers or options; the program must parse and validate them.
#include <stdio.h>
int main(int argc, char **argv) {
printf("argc = %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}./inspect Ada 3 --loudKNOWLEDGE QUIZ
Command-line argument lab
Run ./inspect in the simulated terminal. Add your own arguments and inspect argc and argv. Supports spaces, quotes, and backslash escapes; no system commands are executed.
Enter a command and press Enter. Use ↑ / ↓ for command history.
Bounds checks and conversion
Reading argv[2] requires argc > 2. Numeric conversion should also verify that the full string was consumed and enforce an allowed range. Arguments come only from the launch command; this section performs no file input or output.
KNOWLEDGE QUIZ
Implement a repeat command
Implement ./repeat WORD COUNT.
- Require argc to equal 3; otherwise print usage and return non-zero.
- Convert argv[2] to an integer and reject non-numeric values or counts outside 1–10.
- Print argv[1] on its own line COUNT times.
- Test ./repeat hello 3 and one invalid command.