Return array from function in C

C programming does not require the return to a function of a whole array as an argument. However, you can return a pointer to an array without the need for an index by determining the name of the array.

If you want to return a single-dimensional array from a function, a function returning a pointer should be declared as in the following example:

The second thing to remember is that C does not support returning the address of a local variable outside of the function, so you will have to define it as a static variable.

Now, consider the function below that will generate 20 numbers randomly and return them using an array.

Output:

Return array from function in C

Using Dynamically Allocated Array

Dynamically allocated memory (allocated using new or malloc ()) remains their memory until delete or free) (is removed. So we can build a dynamically allocated array and will be able to delete it once we get out of use.

Output:

Return array from function in C

Using struct:

We can wrap a structure/class list and return a struct/class instance. The explanation for this work is that there are deep copies of array members of structures. A deep copy occurs when the returned instance is copied to main in the program below.

Output:

Return array from function in C

Using static array:

A static variable’s lifetime is throughout the program. So, we can always build and return a static local array.

Output:

Return array from function in C

Pin It on Pinterest

Share This