Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short, we can say that array is a collection of variables of the same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables individually, then it becomes a very tedious task. In such a case, we create an array of variables having the same type. Each element of an array can be accessed using an index of the element.
Let's first see how to pass a single-dimensional array to a function.Passing array to a function
In the above program, we have first created the array arr and then we pass this array to the function getarray(). The getarray() function prints all the elements of the array arr.
Passing array to a function as a pointer
Now, we will see how to pass an array to a function as a pointer.
In the above code, we have passed the array to the function as a pointer. The function printarray() prints the elements of an array.
Note: From the above examples, we observe that array is passed to a function as a reference which means that array also persist outside the function.
How to return an array from a function
Returning pointer pointing to the array
In the above program, getarray() function returns a variable 'arr'. It returns a local variable, but it is an illegal memory location to be returned, which is allocated within a function in the stack. Since the program control comes back to the main() function, and all the variables in a stack are freed. Therefore, we can say that this program is returning memory location, which is already de-allocated, so the output of the program is a segmentation fault.
There are three right ways of returning an array to a function:
Returning array by passing an array which is to be returned as a parameter to the function.
Returning array using malloc() function.
Using Static Variable
In the above code, we have created the variable arr as static in getarray() function, which is available throughout the program. Therefore, the function getarray() returns the actual memory location of the variable 'arr'.
Using StructureThe structure is a user-defined data type that can contain a collection of items of different types. Now, we will create a program that returns an array by using structure.