In the previous chapter, we've learned how to return an array from a function in C, similarly, C allows you to return a pointer from a function. To do this, you must declare a function that returns a pointer, as follows:
1 int * myFunction ()2{3. 4 . 5 . 6 }
In addition, C does not support returning the address of a local variable outside of a function unless the local variable is defined as a static variable.
Now, let's look at the following function, which generates 10 random numbers and returns them using the array name that represents the pointer (that is, the address of the first array element), as follows:
1#include <stdio.h>2#include <time.h>3#include <stdlib.h>4 5 /*function to generate and return a random number*/6 int*getrandom ()7 {8 Static intr[Ten];9 inti;Ten One /*Set seed*/ A Srand ((unsigned) time (NULL)); - for(i =0; I <Ten; ++i) - { theR[i] =rand (); -printf"%d\n", R[i]); - } - + returnR; - } + A /*to invoke the main function that defines the function above*/ at intMain () - { - /*a pointer to an integer*/ - int*p; - inti; - inp =getrandom (); - for(i =0; I <Ten; i++ ) to { +printf"* (p + [%d]):%d\n", I, * (P +i)); - } the * return 0; $}
When the above code is compiled and executed, it produces the following results:
1 15231980532 11872141073 11083009784 4304949595 14213012766 9309710847 1232504848 1069321409 1604461820Ten 149169022 One* (P + [0]) :1523198053 A* (P + [1]) :1187214107 -* (P + [2]) :1108300978 -* (P + [3]) :430494959 the* (P + [4]) :1421301276 -* (P + [5]) :930971084 -* (P + [6]) :123250484 -* (P + [7]) :106932140 +* (P + [8]) :1604461820 -* (P + [9]) :149169022
C returning a pointer from a function