Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading