How to return an array from a function?
Returning array as a whole is not possible in C language.
There are a couple of alternatives ways to have array values returned from a function.
- Encapsulate an array within a structure and then return the structure.
- Dynamically allocate space for the array and then return the pointer to that allocated space.
Lets start with an example of function returning a structure type object, which encapsulates an array:
/*Below is a structure encapsulating an integer array */
struct myIntegerArrayStruct x;
/* From here you have the returned value of array in x.myArray */
struct myIntegerArrayStruct foo()
struct myIntegerArrayStruct y;
/* Do some stuff with the array elements y.myArray, y.myArray etc */
return y; /*Returns the structure object y, which contains the array myArray */
In the above example, myIntegerArrayStruct is a structure which encapsulates an integer array(myArray). So now we can return the structure object, and along with it the array within the structure is also returned.
Now, lets look at the other alternative, which makes allocates array elements dynamically, and then returns its pointer.
int * bar(); /* bar is a function returning pointer to integer(s) */
/*Now we can access the elements returned from the bar function as x, x... etc. */
int * bar()
myDynamicArray=malloc(sizeof(int) * 50);
/* Do some stuff with the array elements myDynamicArray, myDynamicArray etc */
return myDynamicArray; /* Returns the pointer to the dynamically allocated space for integers *
In case if you are wondering why we can't just declare an array within the function and then return that, that is not possible because when we write as:
is an array of some type, it actually returns pointer to the array a
. As the name of the array yields the base address of the array in C language.
Also, we cannot use that pointer because local arrays go out of scope once the function ends.