Accessing command line arguments in C

13,565

Solution 1

The first argument to the program is the name of the program itself. Try using the following instead.

int a = atoi(argv[1]); 
int b = atoi(argv[2]); 

Solution 2

Thats because argv[0] is the name of your executable.

You should use argv[1] and argv[2].

And make sure the count (argc)is 3.

Solution 3

You'll want to use argv[1] and argv[2].

The first element in argv (argv[0]) is the command itself. This will be your program executable name...

Solution 4

Assuming the name of your program is noob.c and you compile it with gcc ./noob.c -o noob. You have to make these changes.

int a = atoi(argv[1]); 
int b = atoi(argv[2]);

You have to run it ./noob 1 2 and voila the output will be 3.

argc is 3 viz number of command line arguments, your input will be the 1st and 2nd values from the command line.

Share:
13,565
PeterK
Author by

PeterK

C++ developer

Updated on June 04, 2022

Comments

  • PeterK
    PeterK about 2 years

    please forgive me if this is a noob question, but i'm a beginner at C, learning only for a while. I tried to write a program that sums up two numbers (provided as params to the application). The code is like this:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main( int argc, char** argv)
    {
       int a = atoi(argv[0]);
       int b = atoi(argv[1]);
       int sum = a+b;
       printf("%d", sum);
       return 0;
    }
    

    But I get incorrect results - huge numbers even for small inputs like 5 and 10. What is wrong here?