tags:

views:

116

answers:

5

Hello,

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 crazy resulst (huge numbers) even for small inputs like 5 and 10. I have no idea what is wrong there, can someone help please?

+14  A: 

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]); 
torak
Aww, you win. Although now that I'm thinking about it, why is he getting "huge numbers"? Shouldn't `atoi(argv[0])` be `0` in pretty much all cases?
Michael Mrozek
Thank you sir! This helped.
PeterK
@Michael Mrozek: Yeah, I agree, but until this error is eliminated determining any other problem isn't going to be possible. Oh well, case solved.
torak
That's what the "accept" button is for. Feel free to use it.
Nathon
I cannot. It says i need to wait 3 more minutes. Don't worry I will accept it. It helped me a lot!
PeterK
@Nathon You need to wait [15 minutes](http://meta.stackoverflow.com/questions/38090/discourage-questions-being-marked-as-answered-within-an-hour-or-so-of-being-poste/44099#44099) after asking a question before you can accept an answer
Michael Mrozek
Woo, good to know.
Nathon
A: 

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

Reed Copsey
+3  A: 

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.

bits
+1 for the check on argc!
Jonathan Leffler
A: 

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.

Praveen S
A: 

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

Alexander Gessler