'How do you return the last element in an array in C?
How do I return the last element in an array? I thought this function would work, as it worked for a similar function that returned the first element.
int END(int arr[]) {
int last;
size_t s = sizeof(arr) / sizeof(arr[0]);
if (s != 0) {
last = arr[s - 1];
return last;
} else {
return -1 ; //END(arr);
}
}
Solution 1:[1]
int END(int arr[]) is adjusted to int END(int* arr), since you can't pass arrays as arguments in C. This means that sizeof(arr) is sizeof(int*), and your calculation for s is wrong.
You can use a macro for this, as the macro argument won't be turned into a pointer implicitly:
#define END(ARR) (ARR)[(sizeof(ARR) / sizeof((ARR)[0])) - 1u]
(Note that there are no arrays of size 0, so your -1 case is redundant)
Solution 2:[2]
You cannot use sizeof inside a function because sizeof(arr) will return the size of the pointer which is generally 8 bytes on a x86_64 architecture. I would not use -1 is an error value because -1 can be an element of the given array. I would prefer the C++ way of npos, returning the maximum value of the data type according to the system architecture.
I would recommend you to get the length of the array as a parameter of the function. Like this:
#include <stdio.h>
#include <limits.h>
int END(int *arr, size_t length); // fix prototype error
/*
@brief Returns the last element of the array `arr`.
@param arr array
@param length array's length
@returns If `arr` is NULL or empty returns INT_MAX, otherwise the last element.
*/
int END(int *arr, size_t length)
{
if (!arr || length == 0) // if arr is NULL
return INT_MAX;
else
return arr[length - 1]; // 0 based indexing system in C
}
int main(void)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
size_t length = sizeof(arr) / sizeof(*arr);
printf("Last element of the array: %d\n", END(arr, length));
return 0;
}
Output:
Last element of the array: 10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Artyer |
| Solution 2 |
