The function and usage of argc and argv in C language

In C programming, you often see the following main function declaration:

int main(int argc, char *argv[])

So what are argc and Argv [] for?
Where argc is the number of arguments entered externally and argv[] is the string array of arguments. This may not be obvious to you, but let’s take a look at an example of the C file argtest.c shown below

#include <stdio.h>
 
int main(int argc, char *argv[])
{
	printf("argc is %d\n",argc);
	for(int i=0;i<argc;i++)
	{
		printf("argv[%d] is: %s\n",i,argv[i]);	
	}
	
	return 0;
}

These lines of code are simple, first printing the value of argc, then printing out the string of all argv[] arrays.
Use the following command to compile the C file

gcc argtest.c -o argtest

After compiling to produce the executable file argtest, execute the following command

./argtest 

The output result of the program is

argc is 1
argv[0] is: ./argtest

This indicates that when the program is executed, only one parameter is entered, and this parameter is the command executing the program.
Execute the following command

./argtest 1234 abcd

The output result of the program is

argc is 3
argv[0] is: ./argtest
argv[1] is: 1234
argv[2] is: abcd

This indicates that the program entered three arguments, and that the last two space-separated strings of the command were passed to the main function.
Through argc and Argv [] we can pass arguments to the program by command.

Read More: