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:
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 ++
You've just finished reading the article "Pass cursor to function in C ++" edited by the TipsMake team. You can save pass-cursor-to-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.
- Tips for effectively importing context into Cursor
- How to write general rules in Cursor - Creating general rules in Cursor
- What is Plan Mode in Cursor? How to use Plan Mode in Cursor?
- Instructions on how to add a GitHub MCP Server to Cursor
- How to Change Your Cursor
- Instructions on how to use Claude in Cursor