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 should read it
- The strerror () function in C
- Malloc () function in C
- Call the function by pointer in C ++
- Cursor this in C ++
- Cursor in C
- Function realloc () in C
- Calloc () function in C
- Function abs () in C
- Pass cursor to function in C ++
- The function rand () in C
- MODE.MULT function - The function returns a vertical array of the most common values in Excel
- GEOMEAN function - The function returns the average of a positive array or range of data in Excel
Maybe you are interested
Journey of encryption technology What is HTTPS? and why is it needed for your site Working hot on the screen, sneaking out on Facebook, have you tried it? Instructions to turn off Tab Post notifications (article cards) on Facebook How to protect your Facebook account from being hacked? Unbelievable coincidence in history makes the whole world astounded