Command-line arguments in C
argv[0] is the program name, and argv[argc] is always NULL.
#include <stdio.h>
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s WORD...\n", argv[0]);
return 1;
}
for (int i = 1; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
printf("argv[argc] is NULL: %d\n", argv[argc] == NULL);
return 0;
}
How it works
argccounts the program name too, so options start at one.- Every argument arrives as a NUL-terminated string.
- Returning non-zero from main signals failure to the shell.
Keywords and builtins used here
NULLcharforifintmainreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 267
- Tokens
- 93
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 1 of 4 in Program environment, step 1 of 14 in Systems programming.