Pointers with argc and argv

Asked

Viewed 96 times

0

I have the following code to run on the terminal. It checks if the first argument is a '+' and then sums up the following 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]) don’t need

1 answer

0


char * argv[] is a pointer vector of the type char *.

Therefore, when accessing one of the elements of this vector through argv[i], you will have a pointer char *.

The function atoi() takes as argument a pointer of type char *, what 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

Exit:

Soma: 15
  • But then the atoi function makes it unnecessary to use pointer in argv[i]?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.