所以我只是有一个简单的问题,我最初认为代码通常是从上到下执行的。所以下面我在 C 中使用指针附加了一个示例,并希望有人向我解释为什么打印 *p1 时的输出是 12 我最初的想法是它会打印 25。谢谢
int a = 10, *p1, *p2;
p1 = &a;
*p1 = 25;
p2 = p1;
*p2 = 12;
printf("%d", *p1);
让我们分解一下:
int a = 10, *p1, *p2; // nothing special
p1 = &a; // p1 now holds the address of a. printf("%d", *p1) would print 10, as it is the current value of a.
// in this point, printf("%d-%d", *p1,a); would print 10-10 (printf("%d",*p2); is UB as p2 is uninitialized)
*p1 = 25; // remember that p1 = &a, meaning that now a = 25. Basically you changed (the variable) a, using a pointer instead of changing it directly.
p2 = p1; // p2 now holds the value of p1, meaning it too points to a
// in this point, printf("%d-%d-%d", *p1,*p2,a); would print 25-25-25
*p2 = 12; // *p2 = 12, and so does *p1, and so does a
// in this point, printf("%d-%d-%d", *p1,*p2,a); would print 12-12-12
printf("%d", *p1);
你应该记住,a
是一个int
保存的整数值,并且p1,p2
是int *
该保持的地址int
。在 之后p1 = &a
,每一个改变a
都意味着*p1
改变了,因为*p1
实际上是*(&a)
[ which is...a
]。之后p2 = p1
,同样适用于p2
。
我最初认为代码通常是从上到下执行的。
嗯,确实如此:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句