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