我分配了一个由3个元素组成的int数组,并考虑了以下代码:
int a[3];
for(int i = -2; i < 3; ++i){
a[i] = i;
cout<<a[i]<<" ";
}
Run Code Online (Sandbox Code Playgroud)
这是它的输出:
-2 -1 0 1 2
Run Code Online (Sandbox Code Playgroud)
似乎数组a有5个分配的空间,而a在这些空间的中间。有任何想法吗?
为了解释负索引是如何工作的,首先必须学习(或记住)对于任何数组,指针a和索引i,表达式a[i]等于*(a + i)。
这意味着您可以拥有一个指向数组中间元素的指针,并将其与正或负索引一起使用,这是简单的算法。
例:
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)
Run Code Online (Sandbox Code Playgroud)
在图形上可以看到它像
+ ------ + ------ + ------ + | a [0] | a [1] | a [2] | + ------ + ------ + ------ + ^ ^ ^ | | | p-1 p p + 1