C Tutorial C References

C - Returning an array from a function



C does not allow to return an entire array from a function. However, a pointer to an array can be returned by specifying the array's name without an index.

Consider a function called MyFunction which returns pointer to a single-dimension array, the following syntax can be used:

Syntax

//returns pointer to 1-D array of type int
int * MyFunction() {
  statements;
}

Example: returning a 1-D array

Consider the example below which generate 10 random numbers between 1 and 1000 and return them using an array.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

//function to generate and return 10 
//random numbers between 1 and 1000
int * getRandom(){

  static int rand_vec[10];

  //initialize random seed
  srand (time(NULL));
   
  for(int i = 0; i < 10; ++i) {
    rand_vec[i] = rand() % 1000 + 1;
    printf("%i\n",rand_vec[i]);
  }

   return rand_vec;
}


int main () {
  //a pointer to an int
  int *p;

  p = getRandom();
   
  for(int i = 0; i < 10; i++) {
    printf("*(p + %i) = %i\n", i, *(p+i));
  }

  return 0;
}

The output of the above code will be similar to:

634
507
167
262
230
998
197
966
390
551
*(p + 0) = 634
*(p + 1) = 507
*(p + 2) = 167
*(p + 3) = 262
*(p + 4) = 230
*(p + 5) = 998
*(p + 6) = 197
*(p + 7) = 966
*(p + 8) = 390
*(p + 9) = 551

❮ C - Arrays