Does array[-1] give the last element in the array?
No, accessing elements outside of the index range is undefined behavior. In your case, the element at the address just prior to the beginning of your array is set to 27.
Since accessing array elements in C is nothing more than doing "straight" pointer arithmetic, passing negative indexes is not disallowed. You could construct a legitimate use case where indexes are negative and positive:
int raw[21], *data = &raw[10];
for (int i = -10 ; i <= 10 ; i++) {
data[i] = i;
}
No; array[-1]
will not access the last element. It's more likely that the memory location just before the array has 27
stored in it. Try this:
array[4] = 27;
array[-1] = 0;
Then test whether array[-1] == array[4]
. They will not be equal (assuming your program doesn't crash when assigning to array[-1]
).
Accessing arrays with index out of bounds does not always crash your program. If the memory accessed by -1 is under your program control than an undefined value will pop out (which was stored by some other data created by your program). In your case it is mere coincidence.