C returns a pointer from a function
In the last chapter, we have learned the C language how to return an array from a function. Similarly, C allows you to return from the function pointer. To do this, 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 the name of the array that represents pointers (ie, address of the first array element) to return them, as follows:
#include <stdio.h> #include <time.h> #include <stdlib.h> /* 要生成和返回随机数的函数 */ int * getRandom( ) { static int r[10]; int i; /* 设置种子 */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf("%d\n", 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:
1523198053 1187214107 1108300978 430494959 1421301276 930971084 123250484 106932140 1604461820 149169022 *(p + [0]) : 1523198053 *(p + [1]) : 1187214107 *(p + [2]) : 1108300978 *(p + [3]) : 430494959 *(p + [4]) : 1421301276 *(p + [5]) : 930971084 *(p + [6]) : 123250484 *(p + [7]) : 106932140 *(p + [8]) : 1604461820 *(p + [9]) : 149169022