Today, there is a problem with the question of assigning a pointer to a function in C + +. The following phenomena can be seen first:
void Test (int *p) { p = NULL;} int main (int argc, char *argv[]) { qcoreapplication A (argc, argv); int *t, y = ten; t = &y; Test (t); return a.exec ();}
I was a little surprised at the result, I always thought that the pointer will be passed, and the pointers are also changed, but the pointer is also a variable, if we want to change it, we must find its address in memory, that is, the address of the pointer. In other words, in a function, if the address of the pointer is assigned, in fact, the original pointer can not be changed!
void Test (int **p) { *p = NULL;} int main (int argc, char *argv[]) { qcoreapplication A (argc, argv); int *t, y = ten; t = &y; Test (&t); return a.exec ();}
In addition, assigning values by reference can also solve this problem:
void Test (int &p) { int n = 9; p = N;} int main (int argc, char *argv[]) { qcoreapplication A (argc, argv); int T, y = ten; t = y; Test (t); return a.exec ();}
In addition, you can modify what the pointer points to, instead of modifying the pointer address, or you can change the content.
Example 1:
void Test (int *p) { int n = 9; *p = n;} int main (int argc, char *argv[]) { qcoreapplication A (argc, argv); int *t, y = ten; t = &y; Test (t); return a.exec ();}
Example 2:
void Test (int *p) { int n = 9; *p = n;} int main (int argc, char *argv[]) { qcoreapplication A (argc, argv); int T, y = ten; t = y; Test (&t); return a.exec ();}
C + + pointer parameter assignment problem