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 either a function, you should declare a function returning a pointer, as done in the example below:

The second thing to keep in mind is that C doesn’t support trying to return a local variable’s address outside the function, so you’ll need 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. Deep copy occurred when we 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