Latest web development tutorials

C returns an array from a function

C array C array

C language is not allowed to return a complete array as a parameter. However, you can specify the array name without an index to return a pointer to an array. We will explain the pointer in the next chapter of this knowledge, you can skip this chapter, and so understand the concept of C pointers after, come to learn in this chapter.

If you want to return a one-dimensional array from a function, you must declare a function returning a pointer, as follows:

int * myFunction()
{
.
.
.
}

In addition, C does not support returning a local variable outside the function's address, unless the definition of local variables asstatic variables.

Now, let's look at the following function, which will generate 10 random numbers, and use an array to return them, as follows:

#include <stdio.h>

/* 要生成和返回随机数的函数 */
int * getRandom( )
{
  static int  r[10];
  int i;

  /* 设置种子 */
  srand( (unsigned)time( NULL ) );
  for ( i = 0; i < 10; ++i)
  {
     r[i] = rand();
     printf( "r[%d] = %d\n", i, r[i]);

  }

  return r;
}

/* 要调用上面定义函数的主函数 */
int main ()
{
   /* 一个指向整数的指针 */
   int *p;
   int i;

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

   return 0;
}

When the above code is compiled and executed, it produces the following results:

r[0] = 313959809
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
*(p + 9) : 1990469526

C array C array