程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> c++-C++的數組,為什麼a[i]=i[a],求解釋

c++-C++的數組,為什麼a[i]=i[a],求解釋

編輯:編程綜合問答
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).

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved