Consider this C program that prints the number of command line arguments and the first argument:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%d %s\n", argc, argv[1]);
return 0;
}If you run this program as ./program Hello, what will be the output?
#include <stdio.h> int main(int argc, char *argv[]) { printf("%d %s\n", argc, argv[1]); return 0; }
Remember, argc counts the program name as the first argument.
The argc counts all arguments including the program name, so it is 2. argv[1] is the first argument after the program name, which is "Hello".
Look at this C program:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("No arguments\n");
} else {
printf("Argument: %s\n", argv[1]);
}
return 0;
}What will it print if you run it as ./program with no extra arguments?
#include <stdio.h> int main(int argc, char *argv[]) { if (argc < 2) { printf("No arguments\n"); } else { printf("Argument: %s\n", argv[1]); } return 0; }
Check the value of argc when no extra arguments are passed.
When no arguments are passed, argc is 1 (only the program name). So the condition argc < 2 is true and it prints "No arguments".
Consider this program:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s\n", argv[2]);
return 0;
}If you run this program as ./program one, what happens?
#include <stdio.h> int main(int argc, char *argv[]) { printf("%s\n", argv[2]); return 0; }
Think about how many arguments are passed and what argv[2] points to.
Running with one argument means argc is 2 (program name and "one"). argv[2] is out of bounds and accessing it causes undefined behavior, often a segmentation fault or garbage output.
Which statement best describes how command line arguments are passed to a C program?
Recall the signature of main() that receives arguments.
The standard main() function receives two parameters: argc (argument count) and argv (array of argument strings).
Analyze this program:
#include <stdio.h>
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%d:%s ", i, argv[i]);
}
printf("\n");
return 0;
}What will be printed if you run ./program apple banana?
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("%d:%s ", i, argv[i]); } printf("\n"); return 0; }
Remember the order of arguments in argv.
The first argument argv[0] is always the program name. Then the arguments follow in order: argv[1] is "apple", argv[2] is "banana".