negative index of array

In C/C++, the element a[i] just means go to the ith 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!