负数组索引 [英] Negative array index
问题描述
我有一个定义如下的指针:
I have a pointer which is defined as follows:
A ***b;
按以下方式访问它有什么作用:
What does accessing it as follows do:
A** c = b[-1]
是否因为我们对数组使用了负索引而导致访问冲突?还是类似于*--b
的合法操作?
Is it an access violation because we are using a negative index to an array? Or is it a legal operation similar to *--b
?
EDIT 请注意,负数组索引在 C 和 C++ 中具有不同的支持.因此,这不是骗人的.
EDIT Note that negative array indexing has different support in C and C++. Hence, this is not a dupe.
推荐答案
X[Y]
is identical to *(X + Y)
> 只要 X
和 Y
之一是指针类型,另一个是整数类型.所以 b[-1]
与 *(b - 1)
相同,后者是一个表达式,在格式良好的程序中可能会也可能不会被计算——这一切都取决于b
的初始值!例如,以下完全没问题:
X[Y]
is identical to *(X + Y)
as long as one of X
and Y
is of pointer type and the other has integral type. So b[-1]
is the same as *(b - 1)
, which is an expression that may or may not be evaluated in a well-formed program – it all depends on the initial value of b
! For example, the following is perfectly fine:
int q[24];
int * b = q + 13;
b[-1] = 9;
assert(q[12] == 9);
一般来说,作为程序员,保证指针在您执行操作时具有允许的值是您的责任.如果你弄错了,你的程序有未定义的行为.例如:
In general, it is your responsibility as a programmer to guarantee that pointers have permissible values when you perform operations with them. If you get it wrong, your program has undefined behaviour. For example:
int * c = q; // q as above
c[-1] = 0; // undefined behaviour!
最后,只是为了加强原来的陈述,以下也很好:
Finally, just to reinforce the original statement, the following is fine, too:
std::cout << 2["Good morning"] << 4["Stack"] << 8["Overflow
"];
这篇关于负数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!