Why is a pointer to a pointer incompatible with a pointer to an array?

前端 未结 3 1305
無奈伤痛
無奈伤痛 2021-02-05 18:24

OK, I\'m having trouble understanding pointers to pointers vs pointers to arrays. Consider the following code:

char s[] = \"Hello, World\";
char (*p1)[] = &s         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 18:43

    From what I understand, 's' is a pointer to the first element of the array
    No, s is an array. It can be reduced to a pointer to an array, but until such time, it is an array. A pointer to an array becomes a pointer to the first element of the array. (yeah, it's kinda confusing.)

    char (*p1)[] = &s; This is allowed, it's a pointer to an array, assigned the address of an array. It points to the first element of s.

    char **p2 = &s;
    That makes a pointer to a pointer and assigns it the address of the array. You assign it a pointer to the first element of s (a char), when it thinks it's a pointer to a pointer to one or more chars. Dereferencing this is undefined behavior. (segfault in your case)

    The proof that they are different lies in sizeof(char[1000]) (returns size of 1000 chars, not the size of a pointer), and functions like this:

    template
    void function(char (&arr)[length]) {}
    

    which will compile when given an array, but not a pointer.

提交回复
热议问题