How to access command line parameters in C

Learn how to access command line parameters in C

At yourCProgram, you may need to accept parameters from the command line when the command starts.

For simple needs, all you have to do is changemain()Feature signature from

int main(void)


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

argcIs an integer containing the number of parameters provided on the command line.

argvIs anLarge numbersString.

When the program starts, the parameters will be provided in these two parameters.

Please note,argvArray: program name

Let us take the C compiler used to run the program as an example, as shown below:

gcc hello.c -o hello

If this is our program, we will haveargc4 yearsargvIs an array containing the following

  • gcc
  • hello.c
  • -o
  • hello

Let us write a program that prints the received parameters:

#include <stdio.h>

int main (int argc, char *argv[]) {
  for (int i = 0; i < argc; i++) {
    printf("%s\n", argv[i]);

If our program name ishelloWe run it like this:./hello, We take it as output:


If we pass some random parameters, like this: ./hello a b c we’d get this output to the terminal:


This system works great for simple needs. For more complex needs, there are commonly used packages like getopt.

Download my free C Handbook

More clang tutorials: