Accesing array with pointer

Hello. Im teaching myself c++ with Bruce Eckel's "Thinking in C++" and i have a problem understanding why this doesn't work as espected:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main() {
    int array1[2], array2[2];
    cout << &array1 << endl << &array2 << endl << endl;
    for(int i=0; i<2; i++) {
        array1[i] = array2[i] = i;
    }
    cout << "Array1:" << endl;
    for(int i=0; i<2; i++) {
        cout << array1[i] << endl;
    }
    cout << endl << "Array2:" << endl;
    for(int i=0; i<2; i++) {
        cout << array2[i] << endl;
    }
    cout << endl;
    *(array1+2) = 10;
    cout << endl << "Array2:" << endl;
    for(int i=0; i<2; i++) {
        cout << array2[i] << endl;
    }
}


What im trying to do is write in array2 using a pointer to array1 accessing a position out of the limits of array1. This is the output:
0x7fff7d4fdc40
0x7fff7d4fdc30
0
1

0
1

0
1


Wouldn't *(array1+2) write in array2[0]?

Thanks in advance.
No. Accessing out of bounds of an array is undefined behavior. You can't expect anything reasonable from it.
Thanks for the response.
The thing is that its an exercise from the book and english is not my first language so maybe i understood it wrong:

Create a program that defines two Int arrays, one right after the other. Index off the end of the first array into the second, and make an assignment. Print out the second array to see changes cause by this. Now try defining a char variable between the first array definition and the second, and repeat the experiment.

Its the exercise wrong or am i?

Thanks.
This is obviously terrible to do in practice, but okay as an exercise. The issue is that array1 and array2 aren't laid out in memory in that order, but in the reverse order. I'm assuming you are on a 64bit architecture? Try *(array2+2) = 10;, and check the value of array1.
The two arrays are not necessary placed right after each other in memory. The compiler can place them wherever it wants. From your output you can see that array2 is placed 16 bytes earlier in memory than array1. Note that the array elements only take up 8 bytes (assuming sizeof(int) == 4) so there is some space in between.

Placing the arrays inside a class you get better guarantees about the order of the arrays but there can still be some space in between them.
Omg, i didnt realize that they are in inverse order in memory. Thanks you very much, guys.
Topic archived. No new replies allowed.