开发者

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

int my_array[5] = {0};
int *my_pointer = 0;

my_po开发者_JAVA百科inter = &my_array;  // compiler error
my_pointer = my_array;   // ok

If my_array is address of array then what does &my_array gives me?

I get the following compiler error:

error: cannot convert 'int (*)[5]' to 'int*' in assignment


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.


&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**.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜