Are negative array indexes allowed in C?

2018-12-31 16:38发布

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]

Is that allowed?

I know that arr[x] is the same as *(arr + x). So arr[-2] is *(arr - 2), which seems OK. What do you think?

标签: c arrays
7条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 17:20

Sounds fine to me. It would be a rare case that you would legitimately need it however.

查看更多
登录 后发表回答