Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What does int argc, char *argv[] mean in C/C++?
In C programming, int argc and char *argv[] are parameters of the main function that allow your program to receive command-line arguments when executed. argc stands for argument count and argv stands for argument vector (or argument values).
Syntax
int main(int argc, char *argv[])
{
// Program code
return 0;
}
Parameters
- argc − An integer representing the number of command-line arguments passed to the program (including the program name itself)
- argv[] − An array of character pointers (strings) containing the actual command-line arguments
Example
Here's a complete program that demonstrates how to use argc and argv −
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("This program has %d arguments:\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, argv[i]);
}
return 0;
}
When you compile and run this program with command-line arguments like −
$ ./program hello world
The output will be −
This program has 3 arguments: argv[0]: ./program argv[1]: hello argv[2]: world
Key Points
-
argv[0]always contains the program name or path to the executable -
argcis always at least 1 (for the program name) - Arguments are separated by spaces in the command line
-
argvis null-terminated −argv[argc]is alwaysNULL
Conclusion
Command-line arguments provide a way to pass input data to your C programs at runtime. Understanding argc and argv is essential for creating flexible programs that can accept user input from the command line.
Advertisements
