C & C++: What is the difference between pointer-to and address-of array?

后端 未结 3 2034
情话喂你
情话喂你 2021-01-12 17:30

C++11 code:

int a[3];
auto b = a;       // b is of type int*
auto c = &a;      // c is of type int(*)[1]

C code:

int a[         


        
3条回答
  •  旧时难觅i
    2021-01-12 17:58

    The identity of any object in C++ is determined by the pair of its type and its address.

    There are two distinct objects with the same address in your example: The array itself, and the first element of the array. The first has type int[1], the second has type int. Two distinct objects can have the same address if one is a subobject of the other, as is the case for array elements, class members, and class base subobjects.

    Your example would be clearer if you wrote:

    int a[5];
    int (*ptr_to_array)[5] = &a;
    int * ptr_to_array_element = &a[0];
    

    But you have taken advantage of the fact that the id-expression a for the array decays to a pointer to the array's first element, so a has the same value as &a[0] in your context.

提交回复
热议问题