Arrays need to leave enough space between each offset's address to fit what they're storing. Since you've got an array of 4-byte int
s, there's a four byte difference between each element's address.
Let's look at what an array of 4-byte int
s looks like in memory (on a byte-addressable big-endian system). I'm going to use some different numbers for the values, so we can easily track which bytes belong to which integers. Here's the array I'm using:
int* array = new int[4]
array[0] = 0x1A1B1C1D
array[1] = 0x2A2B2C2D
array[2] = 0x3A3B3C3D
array[3] = 0x4A4B4C4D
And here's what it looks like in memory:
Address Byte Offset Int
...
009694B0 (1A) -- 0 \
009694B1 (1B) | \ 0x1A1B1C1D
009694B2 (1C) | /
009694B3 (1D) / /
009694B4 (2A) -- 1 \
009694B5 (2B) | \ 0x2A2B2C2D
009694B6 (2C) | /
009694B7 (2D) / /
009694B8 (3A) -- 2 \
009694B9 (3B) | \ 0x3A3B3C3D
009694BA (3C) | /
009694BB (3D) / /
009694BC (4A) -- 3 \
009694BD (4B) | \ 0x4A4B4C4D
009694BE (4C) | /
009694BF (4D) / /
...
And here is what it would look like if each value was stored in the next byte, instead of the fourth byte:
Address Byte Offset Int
...
009694B0 (1A) -- 0 0x1A2A3A4A
009694B1 (2A) -- 1 0x2A3A4A4B
009694B2 (3A) -- 2 0x3A4A4B4C
009694B3 (4A) -- 3 0x4A4B4C4D
009694B4 (4B) |
009694B5 (4C) |
009694B6 (4D) /
...
That's not quite what we put in. Only the last number we assigned, 0x4A4B4C4D
came out unscathed. The rest were partially overwritten by the later numbers.