使用示例代码了解 C 中的指针



我正在学习C语言的指针,所以我正在看一个例子。我试图添加评论以了解正在发生的事情。以下代码是否正确?换句话说,我的评论是否正确描述了操作?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(){
int x, y;
int *p1, *p2;
x=-42;
y=163;
p1=&x; //pointer 1 points to the address of x
p2=&y; //pointer 2 points to the address of y
*p1=17; //this just made x=17 because it says that the value at the address where p1 points should be 17
p1=p2; //this just made pointer 1 point at the same place as pointer 2, which means that p1 now points at y
p2=&x; //this just made pointer 2 point at the address of x
//NOW WE HAVE: p1 points at y, p2 points at x, y=17 because of p1
*p1=*p2; //now x=17 as well as y (because the value at the place p2 points, which is x, just became 17)
printf("x=%d, ny=%dn", x, y);
return 0;
}
">

检查调试器",当然。 您也可以在每次设置要检查的值后复制 printf 语句,因为您只是在学习,但这不是好的长期练习。

我不确定您是否已经完全理解了这个概念,并且只是混淆了x和y的错字,或者您是否做出了不正确的假设,但是是的,在您的评论中:

现在我们有:p1 点在 y,p2 点在 x,y=17 因为 p1

此时,P1 和 P2 的位置是正确的,但 y 尚未收到赋值,因为您最初为其提供了值 163。 分配给 *p1 会影响 y,但仅在 p1=p2 行之后。 在此注释的位置,x=17,因为 *p1=17 行排了几行。 y 与初始分配相同。

*

p1=*p2;//现在 x=17 以及 y(因为位置 p2 点的值,即 x,刚刚变为 17(

y在这里变为 17,因为 *p1(现在是 y(被分配了 *p2 中的值,正如您所说,该值为 x。

最新更新