Show a reference to a pointer and pointer using pointers to modify the pointer passed to the method to better use it. (The pointer to the pointer is not a two-dimensional array.)
Why you need to use them
When we pass a pointer as a parameter to a method, we are actually passing a copy of the pointer to the method, or it can be said that the passing pointer is the value of the pointer passing.
If we have a problem modifying pointers inside a method, making changes in the method is just a copy of the modified pointer instead of the pointer itself, and the original pointer retains the original
The value. Let's use the code below to illustrate the problem:
int m_value = 1;void func (int *p) { p = &m_value;} int main (int argc, char *argv[]) { int n = 2; int *PN = &n; cout << *pn << Endl; Func (PN); cout << *PN <<endl; return 0;}
Look at the output.
The output is two X 2
Using pointers to pointers
Show pointers as arguments using pointers
void func (int **p) { *p = &m_value; You can also allocate memory according to your needs *p = new int; **p = 5;} int main (int argc, char *argv[]) { int n = 2; int *PN = &n; cout << *pn << Endl; Func (&PN); cout << *PN <<endl; return 0;}
Let's take a look at the func (int **p) method
- P: Is a pointer pointer, where we do not modify it, otherwise we will lose the pointer to the address of the pointer
- *p: Is the pointer that is pointed to, is an address. If we modify it, the content of the pointer being directed is modified. In other words, we are modifying the *PN pointer in the main () method
- **p: Two times the dereference is the *pn of the main () method
Reference to Pointers
Look again at the reference code of the pointer
int m_value = 1;void func (int *&p) { p = &m_value; You can also allocate memory p = new int according to your needs; *p = 5;} int main (int argc, char *argv[]) { int n = 2; int *PN = &n; cout << *pn << Endl; Func (PN); cout << *PN <<endl; return 0;}
Take a look at the func (int *&p) method
- P: is a reference to a pointer, the *PN in the main () method
- *p: Is the content of the PN point in the main () method.
A reference to pointers and pointers to C + + pointers