A. form void Func (char* ptr).
Note that this is a copy of the pointer, which is essentially the way to pass the value. Create a new pointer variable inside the function, and then assign the value that PTR points to the local pointer variable. Any modification to the local variable's address does not affect PTR.
1 intNewint=1;2 3 voidChangeloc (int*ptr)4 {5ptr=&Newint;6 }7 8 intMain ()9 {Ten intnum=2; One int* ptr=# Acout<<ptr<<Endl; - Changeloc (PTR); -cout<<ptr<<Endl; the } - - /* - Results: + 2 - 2 + */
Two. If you want the view to modify the address of an incoming parameter in a local variable, you can use a pointer reference or pointer to a pointer method.
Source: http://www.cnblogs.com/li-peng/
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.
Three. Effective C + +: Terms of---never return a reference to a local object, and do not return a reference to a pointer inside a function that is initialized with new
1 Char* out()2 {3 /*wrong*/4 5 /*Version16 char* array=new char[10];7 cin>>array;8 return array;9 */Ten One /*Version2 A string k= "Hello,world"; - return k; - */ the -}
A summary of the introduction of pointers as parameters in functions