C Language | Pointers | Parameters of the main() Function
This article explains how to retrieve strings passed by a parent process or command when a program starts.
Command-Line Arguments
The main() function can receive arguments. Where do they come from? When a parent process starts a program, it can pass options as strings. These values are generally provided from the command line. They let you provide information required to run the program.
The main() function receives two arguments. One is the number of command-line arguments. The other is an array of the strings passed as command-line arguments. By convention, the first parameter is named argc and the second is named argv. The value of argc is the argument count, and argv contains the argument strings. In addition to the form without arguments used so far, a typical main() function can use the following form.
main() Function
int main(int argc , char *argv[])
Use this form when processing command-line arguments. The parameter names are optional, but conventionally argc abbreviates argument count and argv abbreviates argument vector. Access the argv array to retrieve the command string at a given index.
Code 1
#include<stdio.h>
int main(int argc , char *argv[]) {
int iCount;
for(iCount = 0 ; iCount < argc ; iCount++)
printf("%d번째 인수 = %s\n" , iCount + 1 , argv[iCount]);
return 0;
}
Code 1 displays the arguments passed to main(). The value of argv[0] is the name of the executed program. If argc is greater than 1, command-line arguments were provided.
Command-line arguments are stored as a table of strings. Check argc and access the appropriate argv element to retrieve an argument. The first actual argument is argv[1], and the last is argv[argc - 1]. The standard also guarantees that argv[argc] is NULL.