Learn C
#include "arraysstrings/argv.h"

Command-Line Arguments (argc & argv) in C

#concept

int main(int argc, char *argv[]) receives the command line: argc counts entries (program name included, so real arguments start at 1), argv holds them as strings with argv[argc] == NULL as terminator. Arguments always arrive as text β€” numbers need strtol/sscanf conversion with validation.

Robust CLIs validate counts (usage message on wrong arity), parse options (getopt for flags), and never trust argument contents (lengths, encoding, injection into shells). argv[0] names the program as invoked β€” handy for usage lines, unreliable for security decisions.

#how it works
1

argc counts, argv holds

./prog a bb has argc 3: argv[0]="./prog", argv[1]="a", argv[2]="bb", argv[3]==NULL.

2

Everything arrives as text

Numbers need conversion: int n = (int)strtol(argv[1], NULL, 10); with errno/range checks for real tools.

3

Validate arity first

if (argc != 3) { fprintf(stderr, "usage: %s in out\n", argv[0]); return 1; } β€” wrong counts get usage, not crashes.

4

Options via getopt

POSIX getopt parses -a -b value flags and --long forms systematically β€” hand-rolled flag loops rot quickly.

#example
#include <stdio.h>
Β 
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: greet NAME\n");
return 1;
}
printf("hello, %s\n", argv[1]);
return 0;
}
Output
hello, ada
1With no name argument (argc 1), the program prints usage and exits 1 instead of reading argv[1] out of bounds.
2Run as greet ada, argv[1] holds the text ada, printed with %s.
3hello, ada prints β€” argument count validated before any access.
#use cases
File tools taking input/output paths as arguments
Usage-message-plus-nonzero-exit on wrong invocation
Converting numeric arguments with validated strtol
Flag parsing with getopt instead of manual loops

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself β€” building beats watching.