C++return pointer c from function+ + pointers C + +pointers in the previous chapter, we've learned about CHow to return an array from a function in + +, similar to C + +allows you to return a pointer from a function. To do this, 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 of a function unless the local variable is defined asStaticvariable. Now, let's look at the following function, which will generateTenrandom number and returns them using the array name that represents the pointer (that is, the address of the first array element), as follows: #include<iostream>#include<ctime>using namespacestd;//function to generate and return a random numberint*Getrandom () {Static intr[Ten]; //Set seedSrand ((unsigned) time (NULL)); for(inti =0; I <Ten; ++i) {R[i]=rand (); cout<< R[i] <<Endl; } returnR;} //to invoke the main function that defines the function aboveintMain () {//a pointer to an integer int*p; P=Getrandom (); for(inti =0; I <Ten; i++) {cout<<"* (P +"<< I <<") : "; cout<< * (p + i) <<Endl; } return 0;} When the above code is compiled and executed, it produces the following results:62472319014687356958071135859764956776133575041377296355153031525917789067081820354158667126415* (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
Returning a pointer from a function