C Tutorial
We can pass arguments to the main function as we do for other functions but we need to specify arguments in command promt for main function.
So passing arguments in command promt to main function is also called command line arguments.
Command line arguments syntax,
$/./a.out arg1 arg2 .... argn
Here argument 0 is the program executable file and actual arguments to the main function from arguments index 1.
This c program gets the command line arguments to the main function and prints the arguments using printf function.
argument 1 is the c program executable file name and actual arguments starting from index 1.
#include<stdio.h> void main(int argc, char *argv[]) { printf("\nNumber of command line arguments: %d", argc); printf("\nArguments:"); for(int i=0;i<argc;i++) { printf("\n%s", argv[i]); } }
Output:
$ cc arguments.c $ ./a.out test1 test2 test3 test4 test5 Number of command line arguments: 6 Arguments: ./a.out test1 test2 test3 test4 test5
declaration of argv[] as an array of pointers to strings.
Variable name is not necessary to use always argc and argv, In place of them we can also use other names as well.
We can use atoi funtion to convert string to integers, so converting above c program to read the integers from command line arguments.
#include<stdio.h> void main(int argc, char *argv[]) { printf("\nNumber of command line arguments: %d", argc); printf("\nArguments:"); for(int i=0;i<argc;i++) { printf("\n%d", atoi(argv[i])); } }
Output:
$ cc arguments.c arguments.c: In function ‘main’: arguments.c:9:20: warning: implicit declaration of function ‘atoi’ [-Wimplicit-function-declaration] printf("\n%d", atoi(argv[i])); $ ./a.out 1 2 3 4 5 Number of command line arguments: 6 Arguments: 0 1 2 3 4 5
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page