concept of argc and argv

This section give you the deep concept of using argc and argv in any of C or C++ program.

A beginner C or C++ programmer always wonder whenever  he saw  following lines in any of the C or C++ source code.
                                 int main (argc, char ** argv)
                                 int main (argc, char * argv[ ])

The concept is  very clear whenever a programmer wants his user should enter some values during run time via command line or whenever  it is required by a program to receive some parameter value from user, we need some mechanism to accept value from command line and use it in program.
Thus we use any of the above two programming style. 
 i.e main() section of our program accept values from the command line which is entered by user as a parameter .
Now the Question is What does argc and argv stands for or what they are ??
We will see one bye one...
1. argc (ARGcount or Argument Count) 
  • Argument Count .
  • Number of arguments passed to main() in argument vector (argv).
  • Value of argc is always ONE greater than the number of command-line argument that the user enters.
2. argv (ARGvalues or Argument vector)
  • Argument Vector
  • An array of string pointers passed to main() function.
  • argv[0] is always the name of the command.
  • argv[argc] is a null pointer.
 
argv[] and argc

       Here 



 argc=,    argv[argc]= NULL







Practical Explanation

Following is a source code .


#include <stdio.h>
void main(int argc, char **argv )
{ int i;
 printf("Commnad Line argument as follows\n");
 printf("Number of command line args. are %d \n\n", argc);
 for (i=0;i<argc;i++)
 printf("argv[%d]: %s\n",i,argv[i]);
}

How to run
  • You can download above code from here.
  • In window simply copy the code in BIN folder of TUROBO C++ and compile & run after opening file.
  • In linux open terminal and perform as shown in below image
argc

Similarly If you also want to print the environment variable.
following is the source code.
#include <stdio.h>
int main(int argc, char **argv, char **env )
{ int i;
 printf("Commnad Line argument as follows\n");
 printf("Number of command line args. are %d \n\n", argc);
 for (i=0;i<argc;i++)
 printf("argv[%d]: %s\n",i,argv[i]);

printf("Environment varialbles as follows\n");
 i=0;
  while(env[i])
  printf("%s\n" , env[i++]);
 return 0;
}


You can download above source code from here



Share this post and spread the knowledge --->

No comments:

Post a Comment