是什么,如果任何一个C ++数组运算符和*(数组+指数)之间的区别? [英] What is the difference between the C++ array operator and *(array + index) if any?

查看:150
本文介绍了是什么,如果任何一个C ++数组运算符和*(数组+指数)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用code像下面的指数项目从数组只是为了提醒自己,数组值是一个指向数组的第一个元素。

I frequently use code like the following to index items out of arrays just to remind myself that the array value is a pointer to the first element of the array.

int array[] = {0,1,2,3,4,5};
*(array + 2) = 42;

虽然它看上去有点难看,不时我居然preFER它传统的 [] 运营商。

int array[] = {0,1,2,3,4,5};
array[2] = 42;

除了让谁​​可以读取我的code在未来有点生气其他人,在那里使用指针运算,以指数比 [] 运营商?

推荐答案

5.2.1 [expr.sub]在C ++的规范说:

Section 5.2.1 [expr.sub] of the C++ spec says:

...这位前pression E1 [E2] 是相同的(由定义) *((E1)+(E2 ))

... The expression E1[E2] is identical (by definition) to *((E1)+(E2))

因此​​,他们是完全一样的,顾名思义。

So they are exactly the same, by definition.

请参阅 http://www.open-std.org /jtc1/sc22/open/n2356/expr.html 一个旧版本的规范。同样的措辞出现在所有的人。

See http://www.open-std.org/jtc1/sc22/open/n2356/expr.html for an older version of the spec. The same wording appears in all of them.

[更新]

注意数组值是一个指向数组的第一个元素是不完全正确,因为的sizeof(阵列)(除其他事项外)将展示。该阵列的衰减的在许多情况下一个指针,但就是不一样的东西。所以,我要说你的风格选择在这里简直是混乱,给其他人,甚至自己...另外,你违反了很常见的和有用的容器访问的抽象,其他评论者指出。也就是说,你在排除了的std ::向量更换阵列的std :: deque的或任何真正的其它容器。只是可怜的风格,海事组织。

Note that "the array value is a pointer to the first element of the array" is not exactly true, as sizeof(array) (among other things) will demonstrate. The array decays to a pointer in many contexts, but that is not the same thing. So I would say your style choice here is simply confusing, to other people and even to yourself... Plus you are violating the very common and useful "container access" abstraction, as other commenters point out. That is, you are ruling out replacing the array with a std::vector or std::deque or really any other container. Just poor style, IMO.

这篇关于是什么,如果任何一个C ++数组运算符和*(数组+指数)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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