PeterK
PeterK

Reputation: 6317

Accessing command line arguments in C

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?

Upvotes: 3

Views: 14463

Answers (5)

Alexander Gessler
Alexander Gessler

Reputation: 46607

That's because argv[0] is the program name, not the first argument (i.e. if you run myapp 4 5, argv becomes myapp, 4, 5).

Upvotes: 0

Praveen S
Praveen S

Reputation: 10393

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.

Upvotes: 1

bits
bits

Reputation: 8340

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.

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564403

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...

Upvotes: 1

torak
torak

Reputation: 5802

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]); 

Upvotes: 18

Related Questions