指向指针的使用给予意外的结果 [英] Pointers to pointer usage giving unexpected result
本文介绍了指向指针的使用给予意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么在第一次印刷声明的main()
,打印11?
#包括LT&;&stdio.h中GT;
无效美孚(INT ** P){
INT J = 11;
* P =安培;焦耳;
的printf(%d个,** P); //打印11
}诠释主(){
INT I = 10;
为int * p =&放;我;
富(安培; P);
的printf(%d个,* P); //打印11
的printf(%d个,* P); //打印随机值
返回0;
}
解决方案
在富()
,你分配一个自动局部变量的地址Ĵ
到 * p
。 富()
执行结束,Ĵ
没有了,因而存在,则使用(derererencing)<$ C $之后C> p 的main()调用的 nofollow的>未定义行为。
现在,UB的输出,那么,的未定义的
Why is the First Printing Statement in main()
, printing 11 ?
#include<stdio.h>
void foo(int ** p){
int j = 11;
*p = &j;
printf("%d ", **p); //Printing 11
}
int main(){
int i = 10;
int *p = &i;
foo(&p);
printf("%d ", *p); //Printing 11
printf("%d ", *p); //Printing Random value
return 0;
}
解决方案
Inside foo()
, you're assigning the address of a automatic local variable j
to *p
. After foo()
has finished execution, j
does not exist anymore and thus, using (derererencing) p
furthermore in main()
invokes undefined behavior.
Now, the output of UB is, well, undefined.
这篇关于指向指针的使用给予意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文