News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

How to return an array from a function?

Started by OmMuruga, Jan 22, 2009, 08:13 PM

Previous topic - Next topic

OmMuruga


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.

   1. Encapsulate an array within a structure and then return the structure.
   2. 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
{
    int myArray[50];
};

int main()
{
    struct myIntegerArrayStruct x;
    x=foo();
    /* From here you have the returned value of array in x.myArray[] */
    return 0;
}

struct myIntegerArrayStruct foo()
{
    struct myIntegerArrayStruct y;

    /* Do some stuff with the array  elements y.myArray[0], y.myArray[1] 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.


include<stdlib.h>

int * bar(); /* bar is a function returning pointer to integer(s) */
int main()
{
    int *x;

    x= bar();

    /*Now we can access the elements returned from the bar function as x[0], x[1]... etc. */
}

int * bar()
{
    int *myDynamicArray;
    myDynamicArray=malloc(sizeof(int) * 50);

    /* Do some stuff with the array  elements myDynamicArray[0], myDynamicArray[1] 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:


          return a;



Where a 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.
:acumen :acumen