Categories: C

Command Line Argument

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

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago