Why is it a compile error to assign the address of an array to a pointer “my_pointer = &my_array”?

后端 未结 3 1293
北荒
北荒 2020-12-09 18:10
int my_array[5] = {0};
int *my_pointer = 0;

my_pointer = &my_array // compiler error
my_pointer = my_array // ok

If my_array is a

相关标签:
3条回答
  • 2020-12-09 18:51

    &my_array is the address at which the value of my_array is stored, i.e., it is the address of the address of the array and has type int**.

    0 讨论(0)
  • 2020-12-09 18:54

    my_array is the name of an array of 5 integers. The compiler will happily convert it to a pointer to a single integer.

    &my_array is a pointer to an array of 5 integers. The compiler will not treat an array of integers as a single integer, thus it refuses to make the conversion.

    0 讨论(0)
  • 2020-12-09 19:02

    This would be a fascinating topic for research on neuroscience, semantics, and software development. Even though we can explain the difference between my_array and &my_array, and even though we can repeat the mantra that "arrays are (or are not) pointers", this distinction is still confusing.

    Usually when we take the address of something with the "&" operation, we arrive at a completely different value.

    int x;
    x=5;
    cout <<x << " "<<&x<<endl;
    

    First of all, let's challenge this intuition. A pointer can be accidentally equal to the value it is pointing at:

    int* x;
    x=(int*)(&x);
    cout <<"same: "<<x << " "<<&x<<endl;
    

    So in some contexts semantically different things can evaluate to the same thing. But just because two expressions are equal in the current context does not mean that they are interchangeable.

    int w=3;
    int* ip=&w;
    void* vp=&w;
    cout <<"Equal: "<<ip<<" "<<vp<<" "<<(ip==vp)<<endl;
    cout <<"But not interchangeable: "<<ip+1<<" "<<vp+1<<" "<<(ip+1==vp+1)<<endl;
    

    The same happens with pointers to arrays. A pointer to an array is often technically "equal" to an array itself, but since they have different semantics, there are situations in which they are not interchangeable. Try this one:

    int my_array[5] = {5,6,7,8,9};
    cout <<my_array[0]<<endl;    // output 5
    cout <<(&my_array)[0]<<endl; // outputs the address of the first element
    cout <<sizeof my_array[0]<<endl; // outputs 4
    cout <<sizeof (&my_array)[0]<<endl; // outputs 20
    
    0 讨论(0)
提交回复
热议问题