负数组索引 [英] Negative array index

查看:113
本文介绍了负数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义如下的指针:

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?

编辑请注意,负数组索引在C和C ++中具有不同的支持.因此,不是骗子.

EDIT Note that negative array indexing has different support in C and C++. Hence, this is not a dupe.

推荐答案

X[Y]*(X + Y)相同,只要XY之一是指针类型并且另一个具有整数类型.因此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\n"];

这篇关于负数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆