Get Last Array Element in C
In C language, you can access the last element of an array by using the array index. Assuming the array is named arr and has a length of n, you can access the last element using arr[n-1]. Additionally, you can also access the last element of an array using pointers, as shown below:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// 访问最后一个元素
int lastElement = arr[n-1];
printf("The last element of the array is: %d\n", lastElement);
// 使用指针的方式访问最后一个元素
int *ptr = &arr[n-1];
printf("The last element of the array (using pointer) is: %d\n", *ptr);
return 0;
}
In the code above, we first calculate the length of the array arr. Then, we access the last element of the array using arr[n-1] and a pointer, and print it out.