Latest web development tutorials

C ++ function returns an array from

C ++ Array C ++ Array

C ++ does not allow a return to full array as a parameter. However, you can specify the array name without an index to return a pointer to an array.

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 <iostream>
#include <ctime>

using namespace std;

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

  // 设置种子
  srand( (unsigned)time( NULL ) );
  for (int i = 0; i < 10; ++i)
  {
    r[i] = rand();
    cout << r[i] << endl;
  }

  return r;
}

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

   p = getRandom();
   for ( int i = 0; i < 10; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }

   return 0;
}

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

624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415

C ++ Array C ++ Array