Pointers with argc and argv

0

I have the following code to run on the terminal. It checks if the first argument is a '+' and then adds the next numbers.

int main(int argc, char *argv[])
{
int i, soma;
char oper;

oper = *argv[1];

soma = 0;


if(oper == '+'){
    for(i = 2; i <= argc; i++){
        soma = soma + atoi(argv[i]);
    }
    printf("Soma: %d", soma);
}

The question is why       oper = *argv[1] needs the pointer while      atoi(argv[i]) do not need

    
asked by anonymous 29.06.2018 / 22:10

1 answer

0

char * argv[] is a vector of pointers of type char * .

So when you access one of the elements of this vector by means of argv[i] , you will have a char * pointer.

The atoi() function is given a pointer of type char * , which makes atoi(argv[i]) perfectly valid.

It would be the same as:

char * p = argv[i];
int n = atoi(p);

When you do something like:

char oper = *argv[1];

You are reading the first character of the second argument from the command line. What would be equivalent to:

char oper = argv[1][0];

Your code could be something like:

#include <stdio.h>

int main( int argc, char * argv[] )
{
    int i = 0;
    int soma = 0;

    char oper = argv[1][0];

    if( oper == '+' )
    {
        for( i = 2; i < argc; i++ )
            soma += atoi( argv[i] );
    }

    printf( "Soma: %d\n", soma );

    return 0;
}

Testing:

./xpto + 1 2 3 4 5

Output:

Soma: 15
    
29.06.2018 / 23:00