在C ++中,"a"和“& a"之间的区别,其中"a"是一个数组 [英] Difference between `a` and `&a` in C++ where `a` is an array

查看:126
本文介绍了在C ++中,"a"和“& a"之间的区别,其中"a"是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码的输出感到困惑.

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&a如何打印相同的表达式但大小不同? 我一直认为,对于任何数组,其名称始终具有值=第一个字节的地址.

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.

&a应该没有意义,因为不能有一个地址(用&运算符获得)到一个地址(a的值).但是代码给出了一个输出,实际上是'a ==& a' 根据输出.

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.

自动转换的指针与使用&显式创建的指针之间几乎没有区别,除了一个是指向单个元素的指针,而另一个是指向整个数组的指针.如果您使用&a[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 ++中,"a"和“&amp; a"之间的区别,其中"a"是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆