Pass cursor to function in C ++

C ++ allows you to pass a pointer to a function. To do this, you simply need to declare the function parameter as in a pointer type.

C ++ allows you to pass a pointer to a function. To do this, you simply need to declare the function parameter as in a pointer type.

In the simple example below, we pass an unsigned long pointer to a function and change the value inside the function, which reflects back while calling the function:

 #include #include using namespace  std ; void  laySoGiay ( unsigned long * par ); int  main  () { unsigned long  sogiay ;  laySoGiay ( & sogiay  ); // in gia tri  cout  << "So giay la: " <<  sogiay  <<  endl ; return 0 ; } void  laySoGiay ( unsigned long * par ) { // Lay so giay hien tai * par  =  time (  NULL  ); return ; } 

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

Picture 1 of Pass cursor to function in C ++

The function, which can accept a pointer, can accept an array as follows:

 #include using namespace  std ; // khai bao ham: double  giaTriTB ( int * arr , int  size ); int  main  () { // mot mang so nguyen co 5 phan tu. int  doanhSoBH [ 5 ] = { 122 , 35 , 27 , 235 , 60 }; double  trungbinh ; // truyen con tro toi mang duoi dang mot tham so.  trungbinh  =  giaTriTB (  doanhSoBH , 5 ) ; // hien thi ket qua   cout  << "Gia tri trung binh la: " <<  trungbinh  <<  endl ; return 0 ; } double  giaTriTB ( int * arr , int  size ) { int  i ,  sum  = 0 ; double  trungbinh ; for ( i  = 0 ;  i  <  size ; ++ i ) {  sum  +=  arr [ i ]; }  trungbinh  = double ( sum ) /  size ; return  trungbinh ; } 

When the above C ++ program is compiled and executed, it gives the following result:

 Gia  tri trung binh la : 95.8 

According to Tutorialspoint

Previous article: Pointers to pointers in C ++

Next article: Returns the cursor from the function in C ++

« PREV POST
READ NEXT »