Understand argc and argv Yung-Hsiang Lu Purdue University
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; }
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } an integer as indexes
%d means the value of an integer This line prints argc's value #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } %d means the value of an integer This line prints argc's value
argc is the number of arguments it is at least one #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } argc is the number of arguments it is at least one
the first argument is the program's name #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } the first argument is the program's name
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } ind is 0, 1, 2, ... argc - 1
and the value of the argument #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } print the index and the value of the argument
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } print an integer
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } print a string
#include <stdio. h> #include <stdlib #include <stdio.h> #include <stdlib.h> int main(int argc, char * * argv) { int ind; printf("argc = %d\n", argc); for (ind = 0; ind < argc; ind ++) printf("argv[%d] = %s\n", ind, argv[ind]); } return EXIT_SUCCESS; } ind is 0, 1, 2, ..., argc - 1 not 1, 2, ..., argc