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:

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

According to Tutorialspoint

Previous article: Pass cursor to function in C ++

Next article: Reference in C ++

3.5 ★ | 2 Vote | 👨 193 Views

Above is an article about: "Returns the pointer from the function in C ++". Hope this article is useful to you. Don't forget to rate the article, like and share this article with your friends and relatives. Good luck!

« PREV POST
NEXT POST »