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
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:And here's what it looks like in memory:
And here is what it would look like if each value was stored in the next byte, instead of the fourth byte:
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.