# C Arrays and Pointers

Hello guys,

some weeks ago I was reading some questions in StackOverflow and one of them really took my attention. I don’t have a great experience with C programming language, but I’ve started developing in C++ and Symbian 3 moths ago, which improved my skills in pointers and memory allocation. Even after some moths programming in C++, I could not understand why in C arrays a == 5[a], can you?

To answer this question, we must understand the behavior of C arrays. What happens in memory when writing:

int array[] = {0, 1, 2, 3, 4, 5};

The first thing to have in mind is that this assignment creates 5 memory “slots” with 32bits each one. A single “slot” has its value and its address, just like a pointer. It’s easy to predict the value of each position value:

array == 0;
array == 1;
(…)

Talking about the variable address, imagine the array is located at address 0x0000. As you already know, in a 32bit platform, an integer has 32bits = 4bytes. So we can conclude that to access any array position we can use the following calculation:

&array == (0 + (0 * 4));
&array == (0 + (1 * 4));
(…)

And it’s exactly what the compiler does. So, when you write array it’s the same of *(0 + (5 * 4)) = *(20) = 5. Easy! However, what about 5[a]? Well, the calculation is similar. Remember that C arrays are nothing just pointers, which means that both declarations below are equivalents:

int array;
int *array;

And when incrementing an array, you are just going to the array’s next position. Which means:

array == *(array + 1);

Now, if we look back to 5[a], what does it looks like? Similar to what I said, 5[a] = *(5 + a) = *(a + 5) = a.

Now, things are making sense.