0

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);
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
bkukan13
  • 11
  • 5

2 Answers2

3

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)

Artyer
  • 31,034
  • 3
  • 47
  • 75
  • If ARR happens to be NULL (it's C after all and you have to expect the unexpected around every corner), your macro will probably produce a segmentation fault. – BitTickler Feb 10 '22 at 05:30
  • @BitTickler If `ARR` is a pointer it will not work at all (and you would want one of these macros to get the size: https://stackoverflow.com/q/19452971) – Artyer Feb 10 '22 at 05:38
  • NOTE: this is not going to work inside a function – Darth-CodeX Feb 10 '22 at 08:02
0

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
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23