1. 值传递
p
作为参数传入函数fun(char* tmp)
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void fun(char* tmp)
{
printf("tmp = %p\n", tmp);
tmp = (char*)malloc(sizeof(char));
printf("tmp = %p\n", tmp);
strcpy(tmp,"hello");
printf("content of tmp = %s\n", tmp);
//free(p)
}
int main(void)
{
char* p = NULL;
printf("p = %p\n", p);
fun(p);
printf("p = %p, content of p = %s\n", p, p);
return 0;
}
p = (nil)
tmp = (nil)
tmp = 0x7fffb7f116b0
content of tmp = hello
p = (nil), content of p = (null)
- 主函数main中,局部的指针变量p入栈。
-
程序执行到fun()函数中,形参tmp拷贝了实参p的值,为NULL。
- 此时:
- p = NULL,&p = 0xYYYY
- tmp = NULL,&tmp = 0xYYYY - offset
- 此时:
- malloc申请了一段内存空间给到tmp,将字符串复制到tmp,没有改变到main中的p指针。
- 此时:
- p = NULL,&p = 0xYYYY
- tmp = 0xMMMM,&tmp = 0xYYYY - offset
- 此时:
2. 址传递
&p
作为参数传入fun(char** tmp)
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void fun(char** tmp){
printf("tmp = %p\n", tmp);
*tmp = (char*)malloc(sizeof(char) * 10);
printf("tmp = %p\n", *tmp);
strcpy(*tmp,"hello");
printf("content of tmp = %s\n", *tmp);
//free(p)
}
int main(void){
char* p = NULL;
printf("p = %p, &p = %p\n", p, &p);
fun(&p);
printf("p = %p, content of p = %s\n", p, p);
return 0;
}
p = (nil), &p = 0x7fffe18d8600
tmp = 0x7fffe18d8600
tmp = 0x7fffd975d6b0
content of tmp = hello
p = 0x7fffd975d6b0, content of p = hello
- 主函数main中,局部的指针变量p入栈。
- &p传入函数fun(char** tmp),tmp的值就是&p,存入fun的栈帧中。
- 此时:
- p = NULL,&p = 0xYYYY
- tmp = 0xYYYY,&tmp = 0xYYYY - offset,*tmp = NULL
- 此时:
- malloc申请了一段内存空间给到 *tmp,*tmp=0xMMMM,tmp=&p,也即p指向0xMMMM,退出fun()后,p还是指向的0xMMMM,被改变。
- 此时:
- p = 0xMMMM,&p = 0xYYYY
- tmp = 0xYYYY,&tmp = 0xYYYY - offset,*tmp =(*0xYYYY) = 0xMMMM
- 此时: