Are negative array indexes allowed in C?

后端 未结 8 2289
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:56

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|         


        
8条回答
  •  误落风尘
    2020-11-22 14:47

    That is correct. From C99 §6.5.2.1/2:

    The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

    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.

提交回复
热议问题