Reputation: 55
When I want to change last element of array,I always use [-1] for last element.
#include <iostream>
using namespace std;
int main(){
int arr[10]{};
arr[0]=10;
arr[-1]=100;
cout<<arr[-1]<<endl;
return 0;
}
Then my teacher say:"C++ doesn't support that kind of behavior with arrays.I should use arr[9] for last elemant and "arr[-1]=100" will actually store 1000 in the area one element before where the array begins. this can cause crash since that value is outside the bounds of the array." Can someone explain why?
Note:I am python programer.When I use -1 in list.I don't have problem in python. Does C++ have different condition ?
Upvotes: 0
Views: 1231
Reputation: 3973
A C-style array (f.ex. int arr[10]
) is just a handle to a reserved piece of memory, and indexing it is the same as taking the address of it and adding the index. That is:
arr[5]
is the same as *(arr + 5)
which is the same as "take the address of arr
+ (5 * sizeof(int) ). Then dereference the result and return whatever it points to". From this you should be able to see that your teacher is correct: arr[-1]
will give you a couple of bytes of memory just before your array and then interpret that as an int.
And that is it! There are no boundary checks and you can't really add them either since the array does not even know how big it is (so, no .length()
property either).
There is a good reason why one of the most common recommendations on this board to new C++ programmers is: Leave C-style arrays alone and use std::vector
(or std::array
) instead. std::vector
is, as far as I know, the closest thing in C++ to the list you are used to in Python (though not the same, f.ex. vector also does not implement the -1 = last element trick).
Upvotes: 1
Reputation: 36483
Your teacher is right. Accessing the array with arr[-1]
is undefined behavior which is not healthy for your code, bad bad. C style arrays in C++ do not have the -1
feature as Python does.
For C style arrays you indeed have to do arr[9]
for the last element. However for C++ style arrays (std::array
) you can use size() - 1
or rbegin()
or back()
.
Upvotes: 6