和了``&放大器之间的区别`;在了`C / C ++其中`了`是一个数组 [英] Difference between `a` and `&a` in C/C++ where `a` is an array
问题描述
我感到困惑以下code的输出。
I am confused about the output of the following code.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int a[] = {1,2,3};
cout << a << " " << &a << endl;
cout << sizeof(a) << " " << sizeof(&a) << endl;
return 0;
}
的输出是
0xbfcd3ae4 0xbfcd3ae4
12 4
哪有 A
和&放大器;一个
打印相同的前pression,但有不同的大小?
我始终认为,任何阵列,它的名字总是有第一个字节的值=地址。
How can a
and &a
print the same expression but have different sizes?
I always thought that for any array, its name always has the value = address of the first byte.
还有&放大器;一个
应该没有什么意义,因为一个不能有一个地址(用&放大器获得;运营商)到地址(的价值)。然而,code给出了一个输出和逸岸'一==&安培;一个'
根据输出。
Also &a
should not make sense, since one cannot have an address (obtained with the & operator) to an address(the value of a). Yet the code gives an output and infact 'a == &a'
according to the output.
同样为什么的输出的sizeof(A)= 12
(这是总的内存占用)
由阵列? A
是一个指针本身的sizeof(A)= 4字节(在我的32位的Ubuntu 11.04)
Similarly why is the output of sizeof(a) = 12
(which is the total memory occupied)
by the array? a
being a "pointer" itself sizeof(a) = 4 bytes (on my 32 bit Ubuntu 11.04)
显然是有我有一些误解。莫非有人排序了这一点给我吗?
Obviously there is some misconception I am having. Could some one sort this out for me ?
推荐答案
这是数组不是指针,而是一个数组的衰减到的当您尝试使用它像一个指针。你的情况自动打印数组的地址,将其转换成一个指针。
An array is not a pointer, but an array decays to a pointer when you try to use it like one. In your case printing the address of the array automatically converts it into a pointer.
有之间的自动转换指针并与&放大器明确创建所述一个差别不大;
,除了一个是指向单个元件,而另一个是一个指向整个阵列。如果你已经使用&放大器;一个[0]
那么他们将是相同的。
There's little difference between the automatically converted pointer and the one created explicitly with &
, except that one is a pointer to a single element while the other is a pointer to the entire array. If you had used &a[0]
then they would be identical.
这篇关于和了``&放大器之间的区别`;在了`C / C ++其中`了`是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!