Programs started from a shell receive argc (argument count) and argv (argument vector). argv[0] is typically the program name.
Signature
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
Run locally: ./main hello world passes two extra strings.
Parsing tips
Validate argc before accessing argv[1]. Use strtol for numeric args with error checking.
Important interview questions and answers
- Q: Type of argv?
A: Array of pointers to null-terminated char strings—char **equivalently. - Q: argc value with no args?
A: At least 1—program name alone.
Self-check
- What is argv[0] usually?
- How do you avoid accessing argv[1] when argc is 1?
Tip: Always guard argv[1] with argc > 1—accessing missing args is out-of-bounds undefined behavior.
Interview prep
- argc minimum?
At least 1 when invoked—
argv[0]is typically the program name.