问题由来:传递一个指针到调用函数中,指针的值却没有改变
参考 [1] https://blog.csdn.net/ddl2111/article/details/80372774
举三个例子说明。
1.test函数在自己的函数栈中定义了两个新的变量int a和int b,a的值取得是main中int变量a的值。b的值取得是main中int变量b的值
zxc@zxc-HP:~/tmp/c/0410$ cat b.c
#include <stdio.h>
int test(int a, int b)
{
a++;
b++;
printf("func test ---address a = %p, b = %p\n",&a, &b);
printf("func test --- a = %d, b = %d\n",a, b);
return 0;
}
void main()
{
int a = 1;
int b = 2;
printf("func test ---address a = %p, b = %p\n",&a, &b);
printf("func before test --- a = %d, b = %d\n",a, b);
test(a, b);
printf("func after test --- a = %d, b = %d\n",a, b);
}
zxc@zxc-HP:~/tmp/c/0410$ ./b.out
func test ---address a = 0x7ffc56e98d80, b = 0x7ffc56e98d84
func before test --- a = 1, b = 2
func test ---address a = 0x7ffc56e98d6c, b = 0x7ffc56e98d68
func test --- a = 2, b = 3
func after test --- a = 1, b = 2
2.test函数在自己的函数栈中定义了两个新的变量int *a和int *b,a的值取得是传入的&a的值,相当与int *a = &a;(第一个只存在于test中,第二个是main中的,所以test中a存的是main a的地址)
zxc@zxc-HP:~/tmp/c/0410$ cat c.c
#include <stdio.h>
int test(int *a, int *b)
{
(*a)++;
(*b)++;
printf("func test ---address &a = %p, &b = %p\n",&a, &b);
printf("func test ---address a = %p, b = %p\n",a, b);
printf("func test --- a = %d, b = %d\n",*a, *b);
return 0;
}
void main()
{
int a = 1;
int b = 2;
printf("func before test --- address a = %p, b = %p\n",&a, &b);
printf("func before test --- a = %d, b = %d\n",a, b);
test(&a, &b);
printf("func after test --- a = %d, b = %d\n",a, b);
}
zxc@zxc-HP:~/tmp/c/0410$
zxc@zxc-HP:~/tmp/c/0410$
zxc@zxc-HP:~/tmp/c/0410$ ./c.out
func before test --- address a = 0x7ffca361e110, b = 0x7ffca361e114
func before test --- a = 1, b = 2
func test ---address a = 0x7ffca361e0f8, b = 0x7ffca361e0f0
func test ---address a = 0x7ffca361e110, b = 0x7ffca361e114
func test --- a = 2, b = 3
func after test --- a = 2, b = 3
3.test函数在自己的函数栈中定义了一个新的变量char *p,*p的值取得是传入的p的值,相当与char *p = p;(第一个只存在于test中,第二个是main中的,所以test中p存的是main p的内容,即nil)
zxc@zxc-HP:~/tmp/c/0410$ cat e.c
#include <stdio.h>
#include <stdlib.h>
int test(char *p)
{
p = (char *)malloc(10);
printf("func test --- %p\n",&p);
printf("func test --- %p\n",p); //会造成内存泄漏
return 0;
}
void main()
{
char *p = NULL;
printf("func before test --- %p\n",&p);
printf("func before test --- %p\n",p);
test(p);
printf("func before test --- %p\n",p);
}
zxc@zxc-HP:~/tmp/c/0410$
zxc@zxc-HP:~/tmp/c/0410$
zxc@zxc-HP:~/tmp/c/0410$
zxc@zxc-HP:~/tmp/c/0410$ ./e.out
func before test --- 0x7ffd7ffd0360
func before test --- (nil)
func test --- 0x7ffd7ffd0348
func test --- 0x11ec420
func before test --- (nil)
注:格式控制符“%p”中的p是pointer(指针)的缩写
printf函数族中对于%p一般以十六进制整数方式输出指针的值,附加前缀0x