gpt4 book ai didi

c - C 中的指针变量

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:51 25 4
gpt4 key购买 nike

所以我有一个简单的问题,我最初认为代码通常是从上到下执行的。因此,下面我在 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,p2int * 保存 int 的地址。在 p1 = &a 之后,对 a 的每次更改都意味着 *p1 也发生了更改,因为 *p1 是实际上 *(&a) [这是...a]。在 p2 = p1 之后,同样适用于 p2


I thought originally that code in general executes from top to bottom.

嗯,确实如此:)

关于c - C 中的指针变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46813457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com