Returns the pointer from the function in C ++

As we have seen how C ++ allows to return an array from a function, similarly, C ++ allows you to return a pointer from a function.

As we have seen how C ++ allows to return an array from a function, 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:

 int * tenHam () { . . . } 

The second thing to keep in mind is that it is not a good idea to return the address of a local variable to the periphery of a function, so you will have to define a local variable as a static variable.

Now suppose the following function will generate 10 random numbers and return them using an array name that represents a pointer, for example, the first address of the first array element.

 #include #include #include using namespace std ; // phan dinh nghia ham de tao va tra ve cac so ngau nhien. int * soNgauNhien ( ) { static int r [ 10 ]; srand ( ( unsigned ) time ( NULL ) ); for ( int i = 0 ; i < 10 ; ++ i ) { r [ i ] = rand (); cout << r [ i ] << endl ; } return r ; } // ham main de goi phan dinh nghia ham tren. int main () { // mot con tro tro toi mot so nguyen. int * p ; p = soNgauNhien (); for ( int i = 0 ; i < 10 ; i ++ ) { cout << "Gia tri cua *(p + " << i << ") : " ; cout << *( p + i ) << endl ; } return 0 ; } 

Running the above C ++ program will produce the following results:

Picture 1 of Returns the pointer from the function in C ++

According to Tutorialspoint

Previous article: Pass cursor to function in C ++

Next article: Reference in C ++

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile