Return array from function in C
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 a function, a function returning a pointer should be declared as in the following example:
int * myFunction() { ….. ….. ….. }
The second thing to remember is that C does not support returning the address of a local variable outside of the function, so you will have to define it as a static variable.
Now, consider the function below that will generate 20 numbers randomly and return them using an array.
#include <stdio.h> /* function to generate and return random numbers */ int * getRandom( ) { static int k[20]; int p; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( p = 0; p < 20; ++p) { k[p] = rand(); printf( "k[%d] = %d\n", p, k[p]); } return k; } /* main function to call above defined function */ int main () { /* a pointer to an int */ int *s; int i; s = getRandom(); for ( i = 0; i < 10; i++ ) { printf( "*(s + %d) : %d\n", i, *(s + i)); } return 0; }
Output:
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.
#include <stdio.h> int* function(int *array) { arr[1] = 20; arr[2] = 40; return array; } int main() { int arr[100]; int* ptr = function(arr); printf("%d %d", ptr[1], ptr[2]); return 0; }
Output:
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. A deep copy occurs when the returned instance is copied to main in the program below.
#include <stdio.h> struct arrayWrap { int array[100]; }; struct arrayWrap function() { struct arrayWrap m; m.array[1] = 25; m.array[2] = 49; return m; } int main() { struct arrayWrap m = function(); printf("%d %d", m.array[1], m.array[2]); return 0; }
Output:
Using static array:
A static variable's lifetime is throughout the program. So, we can always build and return a static local array.
#include <stdio.h> int* function() { static int array[200]; /* Some operations on array[] */ array[4] = 50; array[9] = 80; return array; } int main() { int* ptr = function(); printf("%d %d", ptr[4], ptr[9]); return 0; }
Output: