问题描述
- C++的数组,为什么a[i]=i[a],求解释
-
比如声明一个数组
int a[5]={1,2,3,4,5}这时 a[3] 和 3[a] 的值都是3,求解为什么?
据说是因为i[a]=*(a+i),但是,为什么是这么规定的?是C++内定的规则,还是因为[ ] 中括号除了定义数组,还有更多的意义?求详细解释,非常感谢。
解决方案
是的[]有两个用途,数组声明 和 下标操作符,
注意在Array subscripting部分,E1[E2],只要有一个操作符为指针即可,没有顺序的哦。
实际上在C语言中,Array subscripting是完全可以不要的, 因为
E1[E2]
完全等价于
(*(E1+(E2)))
数组声明
3.5.4.2 Array declarators
Constraints
The expression that specifies the size of an array shall be an
integral constant expression that has a value greater than zero.
Semantics
If, in the declaration `` T D1 ,'' D1 has the form
D[ constant-expression<opt>]
下标操作符
3.3.2.1 Array subscripting
Constraints
**One of the expressions shall have type ``pointer to object type ,''
the other expression shall have integral type, and the result has type
`` type .''**
Semantics
A postfix expression followed by an expression in square brackets
[] is a subscripted designation of a member of an array object. The
definition of the subscript operator [] is that E1[E2] is identical to
(*(E1+(E2))) . Because of the conversion rules that apply to the
binary + operator, if E1 is an array object (equivalently, a pointer
to the initial member of an array object) and E2 is an integer, E1[E2]
designates the E2 -th member of E1 (counting from zero).
解决方案二:
a是一个地址值,3是一个偏移量值。a[3]和3[a]都相当于这两个值相加,所以结果都指向同一个地址。
C++中数组与指针在很多方面是一致的,有些类似于相同内容的不同展示方式,但细节上还是有所区别的。