C++ negative array index [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

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?

回答1:

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 


回答2:

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.



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!