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:
According to Tutorialspoint
Previous article: Pass cursor to function in C ++
Next article: Reference in C ++
You've just finished reading the article "Returns the pointer from the function in C ++" edited by the TipsMake team. You can save returns-the-pointer-from-the-function-in-c-.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.