Doubt in pointers

I have been told that following 2 statements are equivalent:

a[5] = 0;
*(a + 5) = 0;

Where a is declared as an array of integers.

But then i think about it, integers are supposed to occupy 4 bytes. How can just adding 5 to the base address allow us to go to the 5th elements address? Shouldnt we add 20 to the base address to get to that element?

Thank you.
closed account (zb0S216C)
You obviously don't understand pointer arithmetic.

When pointers are used in this context, increasing/decreasing the pointer by 1 is equivalent to: Pointer + (Index * sizeof(T)), which effectively moves the pointer (T * Index) address to the left or right (big/little endian).

If we had an array of 4 integers, that's 16 bytes. If we displaced a by (2 * sizeof(int)), we would get 8 bytes, which is the amount of addresses between the base address and the second element. The number 2 within the expression is the requested index.

Wazzak
Last edited on
yep. I just printed the addresses and understood. Doubt solved! :)
Topic archived. No new replies allowed.