This question already has an answer here:
I alloced an int array of 3 elements, and thought of this code below:
int a[3]; for(int i = -2; i < 3; ++i){ a[i] = i; cout<<a[i]<<" "; }
Here's its output:
-2 -1 0 1 2
It seems like array a has 5 alloced space, and a is at the middle of those space. Any ideas?
To explain how negative indexes work, you first have to learn (or remember) that for any array or pointer a
and index i
, the expression a[i]
is equal to *(a + i)
.
That means that you can have a pointer to the middle element of an array, and use it with a positive or negative index, and it's simple arithmetic.
Example:
int a[3] = { 1, 2, 3 }; int* p = &a[1]; // Make p point to the second element std::cout << p[-1]; // Prints the first element of a, equal to *(p - 1) std::cout << p[ 0]; // Prints the second element of a, equal to *p std::cout << p[ 1]; // Prints the third element of a, equal to *(p + 1)
Somewhat graphically it can be seen like
+------+------+------+ | a[0] | a[1] | a[2] | +------+------+------+ ^ ^ ^ | | | p-1 p p+1
That is something you should never ever do! C++ doesn't check the boundaries of built in plain arrays so technically you can access locations which are out of the allocated space (which is only 3 ints not 5) but you will ultimately produce errors.
When I ran this on my own IDE (Visual Studio 2017) it threw an exception stating that the stack around the array had become corrupted. What I think is happening is that 3 spaces in memory are being allocated but you force the array to write to five spaces, those preceding and after the initial allocation. This will work technically, but is definitely not recommended. You are basically writing over top of something in your memory and that can have bad consequences when done in large arrays.