Twi*_*ard 0 c c++ arrays pointers
C 数组允许负索引,但我想不出它的用途,因为你永远不会在负索引处有元素。
当然,你可以这样做:
struct Foo {
int arr1[3] = { 1, 2, 3 };
int arr2[3] = { 4, 5, 6 };
};
int main() {
Foo foo;
std::cout << foo.arr2[-2] << std::endl; //output is 2
}
Run Code Online (Sandbox Code Playgroud)
但你为什么想做这样的事情呢?无论如何,什么时候需要对数组进行负索引,以及您会在哪些域中执行此操作?
请记住,当您对数组进行索引时,您将获得索引处的元素N,即 处的元素&array[0] + sizeof(array[0]) * N。
假设您有以下代码:
#include <stdio.h>
int main()
{
int a[5] = {5, 2, 7, 4, 3};
int* b = &a[2];
printf("%d", b[-1]); // prints 2
}
Run Code Online (Sandbox Code Playgroud)