I always include the int argc and char *argv[] in my main(), but I never really use it. Reason is, I don't know how to use it, or what they even do. The programming book I have doesn't really do a good job explaining it. Don't they have something to do with Windows programming or something? I have no idea. Can someone kinda dumb it down for me? Everywhere on the internet people say its a complex subject. Thanks for any help.
They don't need to be included with a program. For example, you'll see most people just use int main() for their code.
However, if you include them they can be used like regular variables if you so chose. You should be able to create values for these variables when running the program in the command prompt. Assuming you are using Visual C++ compiler, you can run the Command prompt for the Visual C++ and type the following:
#include <stdio.h>
int main (int argc, char *argv[])
{
int count;
printf ("This program was called with \"%s\".\n",argv[0]);
if (argc > 1)
{
for (count = 1; count < argc; count++)
{
printf("argv[%d] = %s\n", count, argv[count]);
}
}
else
{
printf("The command had no other arguments.\n");
}
return 0;
}
This will pass values to main. But again, what you type in the command prompt will differ on the compiler / operating system.
Just look at them as variables that can be used in your program. They are typically only used for command line programs where the variables would be entered as you go to run the program in the command prompt. But as you can see in the example program above you can also compile it like a normal program and use the parameters like regular variables.
Main is a function, and argc and *argv[] are variables that are declared as parameters in the function. It acts like any other function in this instance.
But, your main function is not required to have parameters and therefore these are not required for your program to run.
If you know UNIX/linux
you can see the line ls -l
here ls is a program just like the one you write with parameter -l
here argc=2
and argv={"ls","-l"}
argv[0]="ls"
argv[1]="-l" //not only "l"
P.S.: the - is not a must for parameters but this is how ls (and most shell) programs work
for example take this program (sum_2)
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<stdio.h>
#include<unistd.h>
int main(int argc,char* argv[])
{int a,b;
if(argc!=3)
{
printf("error"); //it is a basic program which only takes 2 parameters
exit(0);
}
a=atoi(y[1]); //y[1] is a string thus we have to transform it a integer
b=atoi(y[2]);
printf("%d",a+b);
}
In the shell (or cmd for windows) we type: (something similar in cmd-I don't know the exact syntax probably the same) ./sum_2 3 5 parameters separated by spaces