GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Is there a way to return an array in C from a user defined function?

asked Jan 26, 2017 by anonymous

1 Answer

Following points will make your doubt clear:

1) C does not allow returning an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer .

2) Note that C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.

Below is an example to make it clear to you :

#include <stdio.h>

/* function */
int * returnArray( ) {

   static int  r[10];
   int i;
  
   for ( i = 0; i < 10; ++i) {
      r[i] = i ;
   }

   return r;
}

/* Driver function*/
int main () {

   /* a pointer to an int */
   int *p;
   int i;
	
   p = returnArray();
   for ( i = 0; i < 10; i++ ) {
      printf( "%d ", p[i]);
   }

   return 0;
}

Output: 

0 1 2 3 4 5 6 7 8 9

 

Hope it helped.Do let me know if there is any confusion and do up vote it if you are satisfied.

Thank you

answered Jan 28, 2017 by Mazhar MIK
...