c++ last element of array
int arr[] = {10, 20, 30, 40, 50};
int lastElement = arr[sizeof(arr)/sizeof(arr[0]) - 1];
Explanation:
- arr
is an array of integers with elements: 10, 20, 30, 40, 50.
- sizeof(arr)
returns the total size in bytes occupied by the array arr
.
- sizeof(arr[0])
returns the size in bytes of the first element of the array arr
, which is also the size of each element in the array.
- sizeof(arr)/sizeof(arr[0])
calculates the total number of elements in the array arr
.
- arr[sizeof(arr)/sizeof(arr[0]) - 1]
accesses the last element of the array using the total number of elements in the array and subtracting 1.