Search code examples
arrayscpointersreturn-valuefunction-definition

C Return Value from Function Best Practice


What option is recommended in C to return an array from a function?

Option 1:

void function_a(int *return_array){
    return_array[0] = 1;
    return_array[1] = 0;
}

Option 2:

int* function_b(){
    int return_array[2];
    return_array[0] = 1;
    return_array[1] = 0;
    return return_array;
}

Solution

  • This function

    int* function_b(){
        int return_array[2];
        return_array[0] = 1;
        return_array[1] = 0;
        return return_array;
    }
    

    returns a pointer to the first element of a local array with automatic storage duration that will not be alive after exiting the function.

    So the returned pointer will be invalid and dereferencing such a pointer invokes undefined behavior.

    You could return a pointer to first element of an array from a function if the array is allocated dynamically or has static storage duration that is when it is declared with the storage class specifier static.

    As for the first function then it will be more safer if you will pass also the number of elements in the array like

    void function_a(int *return_array, size_t n );
    

    and within the function you will be able to check the passed value.