1、通过形参传递一级指针:只在函数内部生效,实际并没有改变指针的指向
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test(char *p){
printf("p1 = %p\n",p);
p = malloc(20);
printf("p2 = %p\n",p);
strcpy(p,"hello world");
printf("p3 = %s\n",p);
}
int main(){
char * p = NULL;
test(p);
printf("p = %p\n",p);
//free(p);
return 0;
}
运行结果:
2、通过形参传递二级指针,在函数内部申请的空间可以在调用位置生效
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test(char **p){
printf("p1 = %p\n",p);//一级指针的地址(&pc)
printf("p2 = %p\n",*p);//一级指针里面的值:NULL
*p = malloc(20);
printf("p3 = %p\n",*p);
strcpy(*p,"hello world");
printf("p4 = %s\n",*p);
}
int main(){
char * pc = NULL;
printf("pc1 = %p\n",&pc);
test(&pc);
printf("pc2 = %p\n",pc);
printf("pc3 = %s\n",pc);
free(pc);
return 0;
}
运行结果: