Come mai il codice
equivale alla notazione puntatore/offsetcodice:arrayPtr[i]
?codice:*(arrayPtr + i)
Come mai il codice
equivale alla notazione puntatore/offsetcodice:arrayPtr[i]
?codice:*(arrayPtr + i)
K. L. Thompson
You can't trust code that you did not totally create yourself.A. Bogk
UNIX is user-friendly, it just chooses its friends.
Perché lo dice lo standard (C++03 §5.2.1 ¶1, C99 §6.5.2.1 ¶ 2). È come chiedere "perché se a-b=c allora b+c=a": perché è questa la definizione stessa differenza.
Tra l'altro, il fatto che valga questa definizione per l'operatore [] con uno qualunque degli operandi interi e l'altro puntatore consente di scrivere espressioni apparentemente assurde come:C++
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2)). [Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. ]
C
A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element 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 element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
infatticodice:int arr[10]; cin>>arr[1]; cout<<1[arr]; // stampa il numero appena inserito
dato che anche nelle somme con puntatori vale la proprietà commutativa.codice:arr[1] = *(arr + 1) = *(1 + arr) = 1[arr]
Amaro C++, il gusto pieno dell'undefined behavior.
Queste espressioni assurde (non solo apparentemente, ma anche psicologicamente!xD) erano proprio il tassello mancante nelle mie conoscenze! Grazie dei chiarimenti!Originariamente inviato da MItaly
Tra l'altro, il fatto che valga questa definizione per l'operatore [] con uno qualunque degli operandi interi e l'altro puntatore consente di scrivere espressioni apparentemente assurde come:
infatticodice:int arr[10]; cin>>arr[1]; cout<<1[arr]; // stampa il numero appena inserito
dato che anche nelle somme con puntatori vale la proprietà commutativa.codice:arr[1] = *(arr + 1) = *(1 + arr) = 1[arr]
K. L. Thompson
You can't trust code that you did not totally create yourself.A. Bogk
UNIX is user-friendly, it just chooses its friends.
Di niente, ciao!
Amaro C++, il gusto pieno dell'undefined behavior.