C++ – Why Next Element of Int Array is Stored 4 Bytes After Previous

c

I have this small code:

int* array_int = new int[10];
    array_int[0] = 1;
    array_int[1] = 2;
    array_int[2] = 3;
    array_int[3] = 4;
    array_int[4] = 5;
    array_int[5] = 6;
    array_int[6] = 7;
    array_int[7] = 8;
    array_int[8] = 9;
    array_int[9] = 10;

    print(array_int);
    print(array_int + 1);
    print(array_int + 2);

The output is this:

Address: 009694B0
Value: 1
Address: 009694B4
Value: 2
Address: 009694B8
Value: 3

The address is stored after 4bytes from previous?

So 009694B0 points to the first byte of int 1?
So 009694B1 points to the second byte of int 1 and so on?

I thought 009694B0 points to int 1 and 009694B1 to int 2 and so on.

Best Answer

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 ints, there's a four byte difference between each element's address.

Let's look at what an array of 4-byte ints 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.