C++ 数组地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8412694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Address of an array
提问by quuxbazer
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.
的输出u
是有道理的。
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?
我的理解是t
和&t[0]
应该有相同的值,但是怎么来&t
的也一样呢?&t 实际上是什么意思?
采纳答案by Mankarse
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.
当t
在表达式中单独使用时,会发生数组到指针的转换,这会产生一个指向数组第一个元素的指针。
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.
当t
用作&
运算符的参数时,不会发生此类转换。所述&
然后明确地需要的地址t
(阵列)。&t
是一个指向整个数组的指针。
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.
数组的第一个元素与整个数组的开头在内存中的相同位置,因此这两个指针具有相同的值。
回答by Abyx
The actual type of t
is int[10]
, so &t
is the address of the array.
的实际类型t
是int[10]
,&t
数组的地址也是。
Also, int[]
implicitly converts to int*
, so t
convertsto the address of the first element of the array.
此外,int[]
隐式转换为int*
,因此t
转换为数组第一个元素的地址。
回答by unwind
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.
没有名为 的变量t
,因为您无法更改它。该名称t
仅指第一个元素的地址(并且还具有与其关联的大小)。因此,获取地址的地址实际上没有意义,C 将其“折叠”为地址。
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.
这应该打印相同的内容,因为没有变量保存 的地址foo
,而可以获取其地址。