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

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

Due to a logical error in my program, the controller accessed the -1 th element of the integer array.

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

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

+6
source share
5 answers

No, access to elements outside the range of indices is undefined behavior. In your case, the element at the address immediately before the start of your array will be 27.

Since accessing array elements in C is nothing more than performing "direct" pointer arithmetic, passing negative indexes is not prohibited. You can build a legitimate use case when the indices are negative and positive:

 int raw[21], *data = &raw[10]; for (int i = -10 ; i <= 10 ; i++) { data[i] = i; } 
+13
source

Not; array[-1] will not get access to the last element. Most likely, the memory in memory in front of the array is stored 27 . Try the following:

 array[4] = 27; array[-1] = 0; 

Then check if array[-1] == array[4] . They will not be equal (if your program does not work when assigning array[-1] ).

+6
source

Accessing arrays with an index outside does not always crash your program. If access to the memory accessed by -1 is under your program control, there will be an undefined dropdown value (which was saved by some other data created by your program). In your case, this is just a coincidence.

+2
source

No, this is not true according to the standard. Accessing an element outside the array causes Undefined Behavior.

Your implementation can (I doubt it!) Provide this functionality; but you really should not rely on him.

+1
source

If you mean C (and you are), then no. If you try to access an array with a negative index, you will get an exception from the limits. However, Lua implements this thing as a function. If you access a Lua array with an index of -1, it will read the last element of the array. Index -2 will read the second-last element and so on.

Side note: you can annoy your colleagues by writing this

 foo = {1,2,3,4,5,6,7,8,9,0} print(foo.length() * -1]) 

It prints 1. Annoying, isn't it.

-4
source

Source: https://habr.com/ru/post/911605/


All Articles