Difference between `a` and `&a` in C++ where `a` is an array

前端 未结 3 1888
一向
一向 2021-02-04 17:00

I am confused about the output of the following code.

#include
#include
using namespace std;
int main()
{
  int a[] = {1,2,3};
           


        
3条回答
  •  太阳男子
    2021-02-04 17:32

    First of all, realize that there is a difference between an object1 and the expression that we use to refer to that object. In your code, a is an expression that refers to an object large enough to store 3 int values.

    Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

    Given a statement like

    cout << a;
    

    the expression a has type "3-element array of int"; since a is not an operand of the sizeof or unary & operators, it will be converted to an expression of type "pointer to int", and the value of the expression will be the address of the first element in the array.

    OTOH, given a statement like

    cout << &a;
    

    the expression a is the operand of the unary & operator, so the rule doesn't apply; instead, the type of the expression is "pointer to 3-element array of int", and the value of the expression is the address of the array.

    In both C and C++, the address of the array and the address of the first element of the array are the same, so both expressions yield the same value, but the types of the two expressions are different (int * vs. int (*)[3]).

    In the statement

    cout << sizeof a; // or sizeof (a)
    

    the expression a is the operand of the sizeof operator, so again, the conversion rule doesn't apply; instead, the expression sizeof a evaluates to the number of bytes used by the array (in this case, 12).

    In the statement

    cout << sizeof &a; // or sizeof (&a)
    

    the expression &a evaluates to the address of the array and has type int (*)[3], so sizeof &a evaluates to the number of bytes used by the pointer type (in your case, 4 bytes).

    In both C and C++, when you declare an array like

    int a[3];
    

    the only storage set aside is for the 3 array elements; there's no separate storage for an a variable that points to the first element of the array (which is why a and &a yield the same value).


    1. In the sense of something that occupies memory, not the sense of an instance of a class

提交回复
热议问题