使用传址的方式才能使针对函数参数所做的处理在函数调用结束后仍然有效,指针参数也是如此。
有如下代码:
#include <stdio.h>
void test(char *p)
{
printf("in test, before assigning, &p = %x, p point to \"%s\".\n", &p, p);
p = "hello";
printf("in test, after assigning, &p = %x, p point to \"%s\".\n", &p, p);
}
int main()
{
char *p = "hi";
printf("before test, &p = %x, p point to \"%s\".\n", &p, p);
test(p);
printf("in main, , after test, &p = %x, p point to \"%s\".\n", &p, p);
return 0;
}
用g++编译,输出结果为:

这种方式为传值方式,只是把字符串“hi”的起始地址值存入形参自身的地址,而存储该起始地址值的地址不会被改变。
如上图输出情况所示,地址0x22ff44存储了字符串“hi”的起始地址值,地址0x22ff20在赋值前存储了字符串“hi”的起始地址,在赋值后存储了字符串“hello”的起始地址。
地址0x22ff44存储的值并没有被改变。
若要将函数的处理在调用结束后仍然有效,则需使用传址的方式,函数参数需使用指向指向指针的指针类型,代码如下:
#include <stdio.h>
void test(char **p)
{
printf("in test, before assigning, p = %x, *p point to \"%s\".\n", p, *p);
*p = "hello";
printf("in test, after assigning, p = %x, *p point to \"%s\".\n", p, *p);
}
int main()
{
char *p = "hi";
printf("before test, &p = %x, p point to \"%s\".\n", &p, p);
test(&p);
printf("in main, , after test, &p = %x, p point to \"%s\".\n", &p, p);
return 0;
}
用g++编译,输出结果为:
使用这种方式就可以在函数中改变地址0x22ff44存储的值了,即将原来存储的字符串“hi”的起始地址值改为字符串“hello”的起始地址值。