Command-line Arguments

Learn how to pass additional parameters to your program by the command-line arguments.

Command-line arguments are those which are not part of the written code, but instead, are received from the terminal in which you compile your code. These arguments can then be used in your code.

The main() function can be defined using two arguments:

  1. int argc

  2. char *argv[]

When your program is executed, the first argument argc, will contain the number of command-line arguments passed to your program, plus one. The first argument is always the name of your program. So in the example above, we check to see if argc<2 because we want at least one extra argument passed to our program in addition to the automatic program name argument.

The second argument argv is a one-dimensional array of strings. As we will see later, the (char *) data type, which is actually a pointer to a character, is typically used in C to represent strings (as an array of characters).

In the example above, we use the atoi() function to convert ascii to integer, in order to convert the command-line argument (the second one, hence argv[1]) which is an ascii string, into an integer n. We then declare an array grades[n] to be of length n.

Here is some code that does nothing except output to the screen the number of input arguments, and their value:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy