C++ - char** argv vs. char* argv[]

后端 未结 7 1164
别跟我提以往
别跟我提以往 2020-12-12 12:09

What is the difference between char** argv and char* argv[]? in int main(int argc, char** argv) and int main(int argc, char* arg

相关标签:
7条回答
  • 2020-12-12 12:59

    There is a difference between TYPE * NAME and TYPE NAME[] in both C and C++. In C++ both types are not interchagneable. For example following function is illegal (you will get an error) in C++, but legal in C (you will get warning):

    int some (int *a[3]) // a is array of dimension 3 of pointers to int
    {
        return sizeof a;
    }
    
    int main ()
    {
        int x[3][3];
        std::cout << some(x)<< std::endl;
        return 0;
    }
    

    To make it legal just change signature to int some (int (*a)[3]) (pointer to array of 3 ints) or int some (int a[][3]). The number in last square brackets must be equal to an argument's. Converting from array of arrays to an array of pointers is illegal. Converting from pointer to pointer to array of arrays is illegal too. But converting pointer to pointer to an array of pointers is legal!

    So remember: Only nearest to dereference type signature doesn't matter, others do (in the context of pointers and arrays, sure).

    Consider we have a as pointer to pointer to int:

    int ** a;
    &a     ->     a    ->    *a    ->    **a
    (1)          (2)         (3)          (4)
    
    1. You cannot change this value, the type is int ***. May be taken by function as int **b[] or int ***b. The best is int *** const b.
    2. The type is int **. May be taken by function as int *b[] or int ** b. Brackets of the array declaratin may be leaved empty or contain any number.
    3. The type is int *. May be taken by function as int b[] or int * b or even void * b
    4. Should be taken as int parameter. I don't want to fall into details, like implicit constructor call.

    Answering your question: the real type of argumets in main function is char ** argv, so it may be easily represented as char *argv[] (but not as char (*argv)[]). Also argv name of main function may be safely changed. You may check it easily: std::cout << typeid(argv).name(); (PPc = pointer to p. to char)

    By the way: there is a cool feature, passing arrays as references:

    void somef(int (&arr)[3])
    {
        printf("%i", (sizeof arr)/(sizeof(int))); // will print 3!
    }
    

    Moreover pointer to anything may be implicitly accepted (converted) by function as void pointer. But only single pointer (not pointer to pointer etc.).

    Further reading:

    1. Bjarne Stroustrup, C++, chapter 7.4
    2. C pointers FAQ
    0 讨论(0)
提交回复
热议问题