Home > Article > Backend Development > How to return array from function in c++
#c How to return an array from a function?
C Returning an array from a function
C Returning a complete array as a function parameter is not allowed. However, you can return a pointer to an array by specifying the array name without an index.
If you want to return a one-dimensional array from a function, you must declare a function that returns a pointer, as follows:
int * myFunction() { . . . }
In addition, C does not support returning the address of a local variable outside a function. Unless local variables are defined as static variables.
Now, let us look at the following function, which will generate 10 random numbers and return them using an array, as follows:
Example
#include <iostream> #include <cstdlib> #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 When the 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
The above is the detailed content of How to return array from function in c++. For more information, please follow other related articles on the PHP Chinese website!