Difference between double pointer and array of pointers

前端 未结 3 1038
花落未央
花落未央 2020-12-05 11:41

In a normal c/c++ program we write main function as either

int main(int c, char **argv)

or

int main(int c, char *argv[])
         


        
3条回答
  •  误落风尘
    2020-12-05 12:03

    When used as a function parameter

    char a[]  // compiler interpret it as pointer to char
    

    is equivalent to

    char *a
    

    and similarly, in main's signature, char *argv[] is equivalent to char **argv. Note that in both of the cases char *argv[] and char **argv, argv is of type char ** (not an array of pointers!).

    The same is not true for the declaration

    char **r;
    char *a[10];
    

    In this case, r is of type pointer to pointer to char while a is of type array of pointers to char.
    The assignment

    r = a;   // equivalent to r = &a[0] => r = &*(a + 0) => r = a
    

    is valid because in this expression again array type a will be converted to pointer to its first element and hence of the type char **.

    Always remember that arrays and pointers are two different types. The pointers and arrays equivalence means pointer arithmetic and array indexing are equivalent.

    Suggested reading:

    • But I heard that char a[] was identical to char *a.
    • Why are array and pointer declarations interchangeable as function formal parameters?

提交回复
热议问题