![]() |
VOOZH | about |
In C, arrays are linear data structures that allow users to store the same data in consecutive memory locations. Returning an array in C can be a little complex because unlike C++, C does not support directly returning arrays from functions. In this article, we will learn how to return an array in C.
Returning an Array from a Function in C
Here, we will discuss each of the above methods one by one with the help of example.
One of the most common ways to return an from a in C is by using . This involves allocating memory for the array within the function and then returning a pointer to this memory.
To return an array using pointer follow the below syntax:
data_type* arr = (data_type*)malloc(n * sizeof(data_type));Here,
The below program demonstrates how we can return an array from a function in C using the using pointers.
Array Elements: 0 2 4 6 8
Time Complexity: O(N), where N denotes the returned array size.
Auxiliary Space: O(N)
Another approach to return an array in C is using the . Once an array is declared static it's lifetime extends beyond the function scopes. The static keyword allows the array to retain its values between different function calls. So we can declare a pointer in the main function to get hold of the static array easily.
static data_type arr[n]Here,
Note: You can return the array name from a function and use a pointer to get hold of the static array wherever you want to use it.
The following program demonstrates how we can return an array from a function in C using the using static arrays.
Array Elements: 0 2 4 6 8
Time Complexity: O(N), where N denotes the returned array size.
Auxiliary Space: O(1), as the array is static once it's size is declared it can't be changed further so it remains constant.
In C we can also use structures to encapsulate arrays and then we can easily return them from functions. Following is the syntax to return an array using structures in C.
struct Struct_name{
data_type arr[n]
};
Here,
Note: To return the array we can return the whole structure from the function and then access the array using the dot operator. We can also return multiple arrays by storing them in a single structure.
The following program demonstrates how we can return an array from a function in C using the using structures.
Array Elements: 0 2 4 6 8
Time Complexity: O(N), where N denotes the returned array size.
Auxiliary Space: O(1), as the size of the array is constant.