Command-Line Arguments (argc & argv) in C
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.
argc counts, argv holds
./prog a bb has argc 3: argv[0]="./prog", argv[1]="a", argv[2]="bb", argv[3]==NULL.
Everything arrives as text
Numbers need conversion: int n = (int)strtol(argv[1], NULL, 10); with errno/range checks for real tools.
Validate arity first
if (argc != 3) { fprintf(stderr, "usage: %s in out\n", argv[0]); return 1; } β wrong counts get usage, not crashes.
Options via getopt
POSIX getopt parses -a -b value flags and --long forms systematically β hand-rolled flag loops rot quickly.
#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;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself β building beats watching.