Returning Arrays
Returning arrays from functions seems like something you may want to do, but is a challenging problem. As we saw, copying arrays requires you to copy each element to the destination array. This means that it is not possible to directly copy the array into a destination using an assignment statement.
Instead of returning an array, the general way to approach this is to pass the array by reference (or as a pointer) and have the function or procedure populate the array. This way the caller is responsible for allocating the space for the array, and the parameter can then refer to this space and update it with the values it can provide.
While you cannot return the array directly, you can return a structure data value that contains an array. So if you wrap your array in a struct, then you can return that struct from a function that initialises the data. This would take more space and time, as the function’s result has to exist and then be copied over the destination variable.
Example
The following code illustrates how to populate an array by passing it to a procedure by reference (as a pointer) and how we can use a struct to return data.