3

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?

2
  • 2
    For debugging a problem, make sure you print the inputs and the outputs. The first thing to do would be to add 'printf("argv[0] = %s\n", argv[0]); printf("argv[1] = %s\n", argv[1]); followed by printf("a = %d\nb = %d\n", a, b); after the calls to atoi(). Had you done that, you probably wouldn't have needed to ask the question. (Don't forget to print a newline after the answer!). Commented Jul 26, 2010 at 19:01
  • Also, this is a C question; #include <cstdlib> is a C++ header. Use #include <stdlib.h>. Commented Jul 26, 2010 at 19:03

5 Answers 5

18

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]); 
Sign up to request clarification or add additional context in comments.

4 Comments

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: Yeah, I agree, but until this error is eliminated determining any other problem isn't going to be possible. Oh well, case solved.
I cannot. It says i need to wait 3 more minutes. Don't worry I will accept it. It helped me a lot!
@Nathon You need to wait 15 minutes after asking a question before you can accept an answer
3

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.

Comments

1

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

Comments

1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.