Home > OS >  How do you return the last element in an array in C?
How do you return the last element in an array in C?

Time:02-10

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);
     }
 }

CodePudding user response:

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)

CodePudding user response:

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
  •  Tags:  
  • c
  • Related