C ++解引用数组 [英] C++ Dereferencing Arrays

查看:268
本文介绍了C ++解引用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有读过关于解引用数组的指针一样东西,我认为这不应该工作。但接下来的code不使用Qt创建者和g ++ 4.8的工作:

I never read anything about dereferencing arrays like pointers and I believe it shouldn't work. But the following code does work using QT Creator and g++ 4.8:

int ar[9]{1,2,3,4,5,6,7,8,9};
cout << *ar << endl; //prints the first element of ar

它是正确的行为或只是编译器固定code?

Is it proper behavior or just the compiler fixing the code?

推荐答案

您不能解引用一个数组,只有一个指针。

You cannot dereference an array, only a pointer.

这里发生的事情是,数组类型的前pression,在大多数情况下,隐式转换(衰变)一个指向数组对象的第一个元素。因此, AR 衰变来&放大器; AR [0] ;提领,让你的AR值[0] ,这是一个 INT

What's happening here is that an expression of array type, in most contexts, is implicitly converted to ("decays" to) a pointer to the first element of the array object. So ar "decays" to &ar[0]; dereferencing that gives you the value of ar[0], which is an int.

这最近我的答案讨论这在一些细节的C.用于C ++类似的规则,但C ++有一些更多的情况下,转换不会发生(其中没有发生在你的code)。

This recent answer of mine discusses this in some detail for C. The rules for C++ are similar, but C++ has a few more cases where the conversion does not occur (none of which happen in your code).

这篇关于C ++解引用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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