James Dickens James Dickens - 3 months ago 62
C++ Question

C++ Arrays and overflow

I am mis-understanding something about the code below. From my understanding the

declaration should return a pointer to the first array of two elements, i.e. [1,2], and so
should return [3,4], which only has 2 elements so how does it make sense to call
(*(tester + 1))[2]
. This example prints the number 5 by the way. Any clarifications much appreciated.

int main() {
int tester[][2]{ 1,2,3,4,5,6 };
cout << (*(tester + 1))[2] << endl;
return 0;


When you declare a 2-dimensional array, all the elements are contiguous. The entire array is a single object, so you're not going out of bounds when you just exceed one of the row limits, so longer as you're still in the array. So the next element after tester[1,1] is tester[2,0], and that's what (*(tester + 1))[2] accesses.