【发布时间】:2012-12-04 12:34:58
【问题描述】:
有人可以向我解释/解释为什么下面代码 sn-p 中 main 函数中变量 i 的值不会通过函数 test1 更改,而它确实通过 test2 更改吗?我认为单个指针应该足以改变 i 的值。为什么我们应该使用双指针?
#include <stdio.h>
void test1(int* pp)
{
int myVar = 9999;
pp = &myVar;
}
void test2(int** pp)
{
int myVar = 9999;
*pp = &myVar;
}
int main()
{
printf("Hej\n");
int i=1234;
int* p1;
p1 = &i;
test1(p1);
printf("does not change..., p1=%d\n",*p1);
test2(&p1);
printf("changes..., p1=%d\n",*p1);
return 0;
}
【问题讨论】:
-
请注意,程序格式错误,因为局部变量的地址被超出其范围使用。
-
我注意到了 test2 中的缺陷,但我故意将其保留在这里,因为它举例说明了要避免的危险情况。感谢所有响应者的启发..
-
我推荐这个有趣的阅读:meta.slashdot.org/story/12/10/11/0030249/… :) 在底部你可以找到一个与 C 相关的问题。