+ 2
c++ Array
Given the Array int a[4] = {2,3,5,7}; I want to output the last item by using cout << a[-1] . But the output is 1983713634. Why is that the case? Thanks
4 Answers
+ 13
For an array of size 4, the valid indices are: 0,1,2,3
So, if you want to access the last element, use a[3] instead.
-1 is invalid index, so it's printing garbage value.
+ 7
As has been pointed out, C++ does not provide the feature of accessing the last element of the array via -1 array index, unlike how some other languages do.
+ 4
Indexing of an array starts from 0.
in your program
a[0]=2;
a[1]=3;
a[2]=5;
a[3]=7;
to print last item .use
cout<<a[3];
since a[-1]; , does not exist.
cout<<a[-1]; gives out garbage output.
+ 3
We cannot directly access the last element in the array
if u want the last element try this code
cout<<a[(sizeof(a)/sizeof(a[0]))-1];