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] == 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] == 0;
array[1] == 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:

address = start_address + (index * size)

&array[0] == (0 + (0 * 4));
&array[1] == (0 + (1 * 4));

And it’s exactly what the compiler does. So, when you write array[5] 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[5];
int *array;

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

array[1] == *(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[5].

Now, things are making sense.
To read more about it, go to the original question here.

See you,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s