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

后端 未结 3 2008
情话喂你
情话喂你 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条回答
  •  有刺的猬
    2021-01-12 17:55

    The sizeof operator should behave differently, for one, especially if you change the declaration of a to a different number of integers, such as int a[7]:

    int main()
    {
        int a[7];
    
        auto b = a;
        auto c = &a;
    
        std::cout << sizeof(*b) << std::endl;  // outputs sizeof(int)
        std::cout << sizeof(*c) << std::endl;  // outputs sizeof(int[7])
    
        return 0;
    }
    

    For me, this prints:

    4
    28
    

    That's because the two pointers are very different types. One is a pointer to integer, and the other is a pointer to an array of 7 integers.

    The second one really does have pointer-to-array type. If you dereference it, sure, it'll decay to a pointer in most cases, but it's not actually a pointer to pointer to int. The first one is pointer-to-int because the decay happened at the assignment.

    Other places it would show up is if you really did have two variables of pointer-to-array type, and tried to assign one to the other:

    int main()
    {
        int a[7];
        int b[9];
    
        auto aa = &a;
        auto bb = &b;
    
        aa = bb;
    
        return 0;
    }
    

    This earns me the error message:

    xx.cpp: In function ‘int main()’:
    xx.cpp:14:8: error: cannot convert ‘int (*)[9]’ to ‘int (*)[7]’ in assignment
         aa = bb;
    

    This example, however, works, because dereferencing bb allows it to decay to pointer-to-int:

    int main()
    {
        int a;
        int b[9];
    
        auto aa = &a;
        auto bb = &b;
    
        aa = *bb;
    
        return 0;
    }
    

    Note that the decay doesn't happen on the left side of an assignment. This doesn't work:

    int main()
    {
        int a[7];
        int b[9];
    
        auto aa = &a;
        auto bb = &b;
    
        *aa = *bb;
    
        return 0;
    }
    

    It earns you this:

    xx2.cpp: In function ‘int main()’:
    xx2.cpp:14:9: error: incompatible types in assignment of ‘int [9]’ to ‘int [7]’
         *aa = *bb;
    

提交回复
热议问题