Example 1: #include <stdio.h> #include <stdlib.h>void fun (char*p) {char c = p[3];//or char c=* (p+3);} int main () {char*p2 = "ABCDEFG"; Fun (p2); system ("pause"); return 0;} Error, because the pointer variable itself cannot be passed to a function should make a copy of the argument and pass it to the called function, that is, to make a copy of the P2, assuming its copy is named _P2, which is passed to the inside of the function is _P2, not P2 itself. Example 2:void getmemory (Char*p,int num) {p = (char*) malloc (num*sizeof (char));} int main () {char*str=null; GetMemory (str,10); strcpy (str, "Hello"); free (str); return 0;}
in the Run strcpy (str, "Hello") When an error occurs, STR is still null, that is, str itself does not change, malloc's memory address is not assigned to STR, but is assigned to _STR, and _str is the compiler automatically allocated and recycled, we simply can not use, so we can not get memory. There are two ways to do this:
Law one: with return
#include <stdio.h> #include <stdlib.h>char*getmemory (char*p,int num) {p = (char*) malloc (num*sizeof (char)) ; return p;} int main () {char*str=null;str=getmemory (str,10); strcpy (str, "Hello"),//free (str);p rintf ("%s\n", str); system ("Pause "); return 0;}
Results:
Hello
Please press any key to continue ...
Method Two : With a level two pointer
#include <stdio.h> #include <stdlib.h>void getmemory (char**p,int num) {*p = (char*) malloc (num*sizeof (char) ); return p;} int main () {char*str=null; GetMemory (&str,10); strcpy (str, "Hello"),//free (str);p rintf ("%s\n", str); system ("pause"); return 0;}
Note that the parameter here is &str rather than STR, so passing in the past is the address of STR, is a value, inside the function, with the key ("*") to unlock: * (&STR), the value is str. So malloc allocates a memory address that is really assigned to the STR itself
Cannot pass the pointer variable itself to a function