/* */ Click to Join Live Class with Shankar sir Call 9798158723

Pointer with return in C++ ?


A Pointer is a variable which can stores a address of another variable.C++ allows to pass pointers to the function as well as return a pointer from a function. This can be achieved by declaring the return type of the function as a pointer.

Q) W.A.P to initialize pointer with return.
#include 
#include 
 
using namespace std;
 
// function to generate and retrun random numbers.
int * getRandom( ) {
   static int  r[10];
 
   // set the seed
   srand( (unsigned)time( NULL ) );
   
   for (int i = 0; i < 10; ++i) {
      r[i] = rand();
      cout << r[i] << endl;
   }
 
   return r;
}
 
// main function to call above defined function.
int main () {
   // a pointer to an int.
   int *p;
 
   p = getRandom();
   for ( int i = 0; i < 10; i++ ) {
      cout << "*(p + " << i << ") : ";
      cout << *(p + i) << endl;
   }
 
   return 0;
}