Command Line Argument

  • April 7, 2022
  • C
Matrix multiplication

When your C programs are run, you can pass some values from the command line to them. These values are known as command-line arguments, and they are frequently useful for your program, particularly when you want to control it from the outside rather than hard-coding those values into the code.

The command-line arguments are handled by the main() function arguments, where argc denotes the number of arguments passed and argv[] denotes a pointer array containing each argument passed to the program.

Example:
#include <stdio.h>

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

   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}

When the above code is compiled and run with only one argument, the following is the result.

$./a.out testing
The argument supplied is testing

When the above code is compiled and run with two arguments, the following result is obtained.

$./a.out testing1 testing2
Too many arguments supplied.

When the above code is compiled and run without any arguments, the following result is obtained.

$./a.out
One argument expected

Note: also read about the Dynamic Memory Allocation

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *