Well... The first thing we have to have and mind here is that a vector, nothing else is a pointer to a certain memory region.
When the code line, int reais[10]
, is executed, 10 integers are allocated and the address of the first item is stored, only.
When you access a certain vector position, reais[6]
for example, what really happens is that the program takes the address of the pointer, that is, of the first value (element) and sums it with the offset you passed times the size of the data. That is, the memory address effectively accessed is reais + 6*tamanho de um inteiro
(multiplication by the size of the data is implicitly done, according to the type of the defined vector), where real is the address of the first element of the vector. In other words, what happens is: *(reais + 6)
. Note that the dereferencing operator is used.
That being said, when you use the notation 6[reais]
, what happens is exactly the same as described above. Only now you change the order of the sum between the address and the offset, ie, *(6 + reais)
.
As the addition is a commutative operation, the result is the same and so we access the same memory address. Soon, reais[6] == 6[reais]
.
This is because [] is an operator (so much so that in C++ you can overload it).
Cool. If it is very similar to the original, it would be good to put a link there to give credit.
– Maniero
An observation regarding the declaration of variables within the for(). In ANSI-C, variables can only be declared after "{" (braces) keys. In this case its scope is limited in the area where it was declared.
– lsalamon