# negative index of array

**URL:** <https://discuss.codechef.com/t/negative-index-of-array/3027>\
**Category:** general\
**Tags:** array, index\
**Created:** [August 22, 2013, 9:56pm UTC](https://discuss.codechef.com/t/negative-index-of-array/3027 "2013-08-22T21:56:30Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![tijoforyou](https://discuss.codechef.com/user_avatar/discuss.codechef.com/tijoforyou/32/9108_2.png) [@tijoforyou](https://discuss.codechef.com/u/tijoforyou)\
**Post date:** [August 23, 2013, 8:15pm UTC](https://discuss.codechef.com/t/negative-index-of-array/3027/3 "2013-08-23T20:15:10Z")

</div>

In C/C++, the element `a[i]` just means go to the `i`th element starting from the base address of array `a`.

So, `a[0]` means the base address of `a` itself. `a[1]` means the address that immediately follows the base address. And so on…

For simplicity, assume that an `int` takes only `1` byte and that the base address of `a` is `1000`. So, `a[0]` is the element in address `1000`, `a[1]` is the element in the address `1001`, …, `a[57]` is the element in the address `1057`, and so on… Definitely, `a[i]` means element in the address `1000 + i`.

So, `a[-1]` means the element in the address `1000 + -1`, which is element in the address `999`.

In other words, the integer, that precedes even the first element of the array.

Now, there are two cases that can arise:

1. The above said location is restricted for access. Then, we get a Runtime Error (Segmentation Fault).
2. No restriction for access. The element at that address can be read from or written into. However, this kind of behaviour is clearly undefined, as to we don’t know what exactly is getting stored in that location.

If we specifically know what is there in that location, it is ok. But otherwise, that code is, allow me to use some compiler warning terminology, dangerous and should not be used.

I am wondering, what exactly that code was trying to do. Can you share the link to the program you were talking about? Someone here could be of better help, making you understand what is going on in that particular program.

Cheers!

---

_[View the full topic](https://discuss.codechef.com/t/negative-index-of-array/3027)._
