简体   繁体   中英

Why there is argv[i][0], whenever I try to do some operation using operator in command line argument in c?

I am learning command line argument in C. There is a section where I am supposed to define the char variable with a position of argv[i]. I tried using argv[2], but it showing some warning ( warning: initialization of 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion] )

whenever, I did argv[2][0], it did worked.

Why there is a 0 in the end. It seemed like a 2d array for me.

#include <stdio.h>
#include <stdlib.h>
int main(int argc,  char *argv[])
{
    int a, b, sum = 0 ;
    char operate = argv[2][0] ; //I tried running it by using argv[2], but it showing a conversion error
    // warning: initialization of 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion].

    if(argv[4])
    {
        printf("Please enter a valid numebr ") ;
        return -1 ;
    }
    a = atoi(argv[1]) ;
    b = atoi(argv[3]) ;

    //now to choose operator
    switch(operate) {
        case '+' :
            sum = a + b;
            break;

        case '-' :
            sum = a - b;
            break;
    }

    printf("The operation is = %d", sum ) ;
}

The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer.

char operate = argv[2][0] ;

Here, argv[2] is a null-terminated array of characters, or a char * . The type of operate is char . You're trying to initialize a char with a char * , hence the warning.

argv[2][0] means the first element of the the char * which is a char . So the definition is valid, and you get no warnings.

argv[2] ---> Apple 
             |
             | 
         argv[2][0]

The above answer assumes that i < argc . Before accessing an argument, you should check whether it is valid or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM