为什么编译器不阻止我使用大于数组长度减一的整数和负整数对数组进行索引?
允许这样做的理由是什么?
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)
但你为什么想做这样的事情呢?无论如何,什么时候需要对数组进行负索引,以及您会在哪些域中执行此操作?