Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does array[-1] give the last element in the array?

Tags:

arrays

c

programming my arduino microcontroller board in C, I noticed a strange behaviour.

Because of an logic mistake in my program the controller accessed the -1th element of an integer array.

 int array[5];

 array[4] = 27;
 // array[-1] gives 27 now.

Is it correct that I get the last element of an array by using -1 as the element selector?

like image 237
danijar Avatar asked Mar 25 '12 16:03

danijar


Video Answer


2 Answers

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;
}
like image 152
Sergey Kalinichenko Avatar answered Oct 13 '22 23:10

Sergey Kalinichenko


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]).

like image 41
Ted Hopp Avatar answered Oct 13 '22 22:10

Ted Hopp