C 中是否允许负数组索引? [英] Are negative array indexes allowed in C?
问题描述
我只是在阅读一些代码,发现此人正在使用 arr[-2]
访问 arr
之前的第二个元素,如下所示:
I was just reading some code and found that the person was using arr[-2]
to access the 2nd element before the arr
, like so:
|a|b|c|d|e|f|g|
^------------ arr[0]
^---------- arr[1]
^---------------- arr[-2]
允许吗?
我知道 arr[x]
和 *(arr + x)
是一样的.所以 arr[-2]
是 *(arr - 2)
,这看起来没问题.你怎么看?
I know that arr[x]
is the same as *(arr + x)
. So arr[-2]
is *(arr - 2)
, which seems OK. What do you think?
推荐答案
这是正确的.来自 C99 §6.5.2.1/2:
That is correct. From C99 §6.5.2.1/2:
下标的定义运算符 [] 是 E1[E2] 是等同于 (*((E1)+(E2))).
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).
没有魔法.这是一个 1-1 的等价关系.在取消引用指针 (*) 时,您需要确保它指向有效地址.
There's no magic. It's a 1-1 equivalence. As always when dereferencing a pointer (*), you need to be sure it's pointing to a valid address.
这篇关于C 中是否允许负数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!