Consider the following C program that prints command line arguments:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%d\n", argc);
return 0;
}If you run this program as ./program arg1 arg2, what will it print?
#include <stdio.h> int main(int argc, char *argv[]) { printf("%d\n", argc); return 0; }
Remember that argc counts the program name as the first argument.
The argc variable counts all arguments including the program name. So ./program arg1 arg2 has 3 arguments total.
Look at this C program that prints the first command line argument:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
printf("%s\n", argv[1]);
} else {
printf("No argument\n");
}
return 0;
}What will it print if run as ./program Hello?
#include <stdio.h> int main(int argc, char *argv[]) { if (argc > 1) { printf("%s\n", argv[1]); } else { printf("No argument\n"); } return 0; }
Remember argv[0] is the program name, argv[1] is the first argument.
The program checks if there is at least one argument after the program name. Since Hello is passed, it prints Hello.
Analyze this C program that prints all command line arguments:
#include <stdio.h>
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%s ", argv[i]);
}
printf("\n");
return 0;
}What will it print if run as ./prog one two?
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); return 0; }
Remember argv[0] is the program name including the path used to run it.
The loop prints all arguments including the program name ./prog followed by one and two, each separated by space.
Consider this C program:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s\n", argv[argc]);
return 0;
}What happens when you run it?
#include <stdio.h> int main(int argc, char *argv[]) { printf("%s\n", argv[argc]); return 0; }
Remember that argv array indices go from 0 to argc - 1.
The argv[argc] is out of bounds because valid indices are 0 to argc - 1. Accessing it causes a segmentation fault.
You want to print the third command line argument in a C program. Which code snippet safely does this?
Remember that argv[0] is the program name, so the first argument is argv[1].
The third command line argument (excluding the program name) is argv[3]. To access it safely, check argc >= 4 since argc includes the program name as the first. Option D does this correctly. Option D accesses the second argument (argv[2]), and D has no bounds check.