首页 > 解决方案 > 使用示例代码理解 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=%d\n", x, y);

    return 0;
}

标签: cpointers

解决方案


“检查调试器”,当然。您也可以在每次设置要检查的值后复制您的 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。


推荐阅读