C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)

先看一个例子:这个程序为什么会崩溃?

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int f(int *q)
 5 {
 6     int a = 10;
 7     q = (int*)malloc(sizeof(int));
 8     *q = a;
 9     return 0;
10 }
11 
12 int main()
13 {
14     
15     int *p = NULL;
16     f(p);
17     printf("%d", *p);
18     return 0;
19 }

此处的q任然是p的一个拷贝,可以通过这个程序证明:

 1 #include <iostream>
 2 
 3 
 4 int f(int *q)
 5 {
 6     std::cout << &q << std::endl;
 7     return 0;
 8 }
 9 
10 int main()
11 {
12     int a = 10;
13     int *p = &a;
14     f(p);
15     std::cout <<  &p;
16     return 0;
17 }

输出为:   ,    说明指针p与指针q的地址是不同的,证明q是p的一个拷贝。

所以第一个程序崩溃的原因:函数中的q其实是实参p的一份拷贝,函数中的操作都是对q进行的,p仍然是NULL,所以输出*p的值产生崩溃!

可以把形参改为二级指针,程序便可以按预想中的情形进行:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int f(int **q)
 5 {
 6     int a = 10;
 7     *q = (int*)malloc(sizeof(int));
 8     **q = a;
 9     return 0;
10 }
11 
12 int main()
13 {
14 
15     int *p = NULL;
16     f(&p);
17     printf("%d", *p);
18     return 0;
19 }
原文地址:https://www.cnblogs.com/FengZeng666/p/9477693.html