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

后端 未结 3 1309
北荒
北荒 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 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 <

    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: "<

    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: "<

    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 <

提交回复
热议问题