Pointer arithmetic
The code:
int** a = new int*[2];
a[0] = new int(1);
a[1] = new int(2);
cout << "a[0] " << a[0] << '\n';
cout << "a[1] " << a[1] << '\n';
cout << "a[2] " << a[2] << '\n';
cout << "a[0] + 1 " << a[0] + 1 << '\n';//WHY THIS ISN'T == a[1] ?
cout << "*(a + 1): " << *(a + 1) << '\n'; //WHY THIS IS == a[1] ?
cout << "a[0] - a[1] " << static_cast<int>(a[0] - a[1])<< '\n';//WHY THIS IS == 16 not 4?
cout << sizeof(int**);
Questions are included next to the relevant lines in the code.
a source to share
a[0] + 1
means 1 is added to the value stored ina[0]
*(a + 1)
means it is 1 * sizeof(int)
added to memory address a and then accesses that address, which means you geta[1]
Read more about pointers here .
As for your last question, there is no guarantee that it will print any particular value, since the two memory addresses should not be contiguous. For me it prints -4
for example.
a source to share
a[0]
and a[1]
are contiguous, and both are pointers, but they do not point to contiguous memory areas.
This is because the memory pointers returned by the operator new
are actually unpredictable.
In other words, there is no guarantee (in fact, the exact opposite) that the chunks of memory returned
a[0] = new int(1);
a[1] = new int(2);
are adjacent.
a source to share