比如聲明一個數組
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).