Show a pointer to a pointer and a pointer that uses pointers to modify the pointers passed to the method to better use it. (The pointer is not a two-dimensional array.)
Why do they need to be used
When we pass a pointer as a parameter to a method, we actually pass a copy of the pointer to the method, or we can say that the pass pointer is the value of the pointer.
If we have a problem modifying the pointer within the method, the modification in the method is just the copy of the modified pointer rather than 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;
}
Check out the output.
The output is two 2
Using pointers to pointers
Show me how to use the pointer as a parameter
void func (int **p)
{
*p = &m_value;
You can also allocate memory according to your requirements
*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 will not modify it, otherwise we will lose this pointer to the pointer address
*p: Is the pointer that is being pointed to, is an address. If we modify it, we modify the contents of the pointer that is being pointed to. In other words, we are modifying the *PN pointer in the main () method
**p: Two-time dereference refers to the contents of *PN in the main () method
References to pointers
Look at the reference code of the pointer again
int m_value = 1;
void func (int *&p)
{
p = &m_value;
You can also allocate memory
p = new int according to your requirements;
*p = 5;
}
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 func (int *&p) method
P: is the reference to the pointer, the *PN in the main () method
*p: is the content that the PN points to in the main () method.
Above this in-depth understanding of C + + pointers and pointers to the pointer is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.