we use main function argument to fetch the data from command line so that these are also called command line parameter. For example: $ls -l -s -o -t $gcc -o object_file let we take an example to understand it in batter way:-->
#include<stdio.h> #include<stdlib.h> int main(int arg,char *argv[]) { int i; for(i=0;i<=arg;i++) { if(argv[i][0]=='-') { printf("option is %s\n",argv[i]+1); } else printf("argument is %d : %s\n",i,argv[i]); } return 0; }
When we run it do like that: $make filename $./filename -l -s -r -t 'ankit'
Main function arguments are Command line arguments/Run time arguments, while calling the function int argc : Counts the number of strings (Argument count) char *c argv[] : Array of strings. where argv[0] gives the current file name and path
The Main function arguments are Command line arguments/Run time arguments, while calling the function int argc : Counts the number of strings (Argument count) char *c argv[] : Array of strings. where argv[0] gives the current file name and path while it is recommended to use pointer fpr arrays using realloc so that we can alloacte the memory at run time
this arguments are very useful during exection time of a program we can pass the argument to the program during execution. argc will tells you number of argument passed argv[] is an array of argument passed suppose ./program arg1 arg2 argc = 3 arg[0] =./program arg[1]=arg1 arg[2]=arg2 and so on this is very helpful when you want to give changeable data again and again during execution time
As we pass arguments in simple function,just like that we can also pass arguments in main function with following syntax int main(int argc,char *argv[ ]) which are called command line argument or run time argument.
As name suggests,arguments will pass at run time where the first argument having zero index will be file name. FOR EXAMPLE: #include<stdio.h>
int main(int argc,char *argv[]) {int i; printf("argc=%d",argc); for(i=0;i<argc;i++) printf("argv at %d is %s",i,argv[i]); return 0; } when one runs the program, output will like this:
./Arguments alpha gamma theeta beeta zeeta argc=6 argv at 0 is ./Arguments argv at 1 is alpha argv at 2 is gamma argv at 3 is theeta argv at 4 is beeta argv at 5 is zeeta