Address of an array

∥☆過路亽.° 提交于 2019-11-26 02:37:54

问题


int t[10];

int * u = t;

cout << t << \" \" << &t << endl;

cout << u << \" \" << &u << endl;

Output:

0045FB88 0045FB88
0045FB88 0045FB7C

The output for u makes sense.

I understand that t and &t[0] should have the same value, but how come &t is also the same? What does &t actually mean?


回答1:


When t is used on its own in the expression, an array-to-pointer conversion takes place, this produces a pointer to the first element of the array.

When t is used as the argument of the & operator, no such conversion takes place. The & then explicitly takes the address of t (the array). &t is a pointer to the array as a whole.

The first element of the array is at the same position in memory as the start of the whole array, and so these two pointers have the same value.




回答2:


The actual type of t is int[10], so &t is the address of the array.

Also, int[] implicitly converts to int*, so t converts to the address of the first element of the array.




回答3:


There is no variable called t, since you can't change it. The name t simply refers to the address of the first element (and also has a size associated with it). Thus, taking the address of the address doesn't really make sense, and C "collapses" it into just being the address.

The same sort of thing happens for the case of functions:

int foo(void)
{
  return 12;
}

printf("%p and %p\n", (void *) foo, (void *) &foo);

This should print the same thing, since there is no variable holding the address of foo, whose address in turn can be taken.



来源:https://stackoverflow.com/questions/8412694/address-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!