在C允许负数组索引? [英] Are negative array indexes allowed in C?
问题描述
我只是读一些code,发现该人已被使用改编[-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]
是允许的?
我知道改编[X]
相同 *(ARR + X)
。因此,改编[-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:
标的德音响nition
运算符[]是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屋!