Different way of accessing array elements in C
Perfectly valid C. From Wikipedia:
Similarly, since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a] (although this form is rarely used).
Wacky, but valid.
It's basically just the way C works. str[5]
is really equivelent to *(str + 5)
. Since str + 5
and 5 + str
are the same, this means that you can also do *(5 + str)
, or 5[str]
.
It helps if you don't think of "5" as an index, but rather just that addition in C is commutative.
str[5]
directly translates to *(str + 5)
, and 5[str]
directly translates to *(5 + str)
. Same thing =)
Similarly, since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a] (although this form is rarely used).
http://en.wikipedia.org/wiki/C_syntax#Accessing_elements
Its all same. *ptr or ptr[0] actually means *(ptr+0). So whenever you write *ptr or ptr[0] it goes as *(ptr+0). Let say you want value at ptr[4] so it means you can also write it as *(ptr+4). Now whether you write it as *(ptr+4) or *(4+ptr), it's same. so just for understading if you can write *(ptr+4) as ptr[4] same way *(4+ptr) is same as 4[ptr]. Please go through http://en.wikipedia.org/wiki/C_syntax#Accessing_elements for more details.