Access command line arguments in C

Please forgive me if this is a question about noob, but I'm new to C, studying only for a while. I tried to write a program that sums up two numbers (provided as parameters for the application). The code looks 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 the wrong results - huge numbers even for small inputs like 5 and 10. What is wrong here?

+3
source share
5 answers

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

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

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

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

And make sure count (argc) is 3.

+3

argv[1] argv[2].

argv (argv[0]) . ...

+1

, noob.c, gcc ./noob.c -o noob. .

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

./noob 1 2, voila - 3.

argc - 3 , 1- 2- .

+1

, argv[0] - , (.. myapp 4 5, argv myapp, 4, 5).

0

Source: https://habr.com/ru/post/1756620/


All Articles