j = * x; x =& j; (* x)= 3;为什么会改变c中j的值

时间:2017-10-15 14:02:47

标签: c pointers

我写了那么简单的代码:

int main()
{
    int i,j;
    int *x; // x points to an integer
    i = 1;
    x = &i;
    j = *x;
    printf("i = %d, j = %d\n", i, j); //i = 1, j = 1
    x = &j;
    (*x) = 3;
    printf("i = %d, j = %d", i, j); // i = 1, j = 3
}

正如我们在这里看到的那样,在(*x) = 3;之后,有人可以解释这里发生的事情,j的值会发生变化。

2 个答案:

答案 0 :(得分:0)

int main()
{
    int i,j;   // declaration of i and j
    int *x;    // x points to an integer
    i = 1;     // initialization of i = 1
    x = &i;    // initialization of x = address of i
    j = *x;    // initialization of j = value of what pointed by x => j = 1

    printf("i = %d, j = %d\n", i, j); //i = 1, j = 1

    x = &j;    // assign to x the address of j
    (*x) = 3;  // assign 3 to what pointed by x 
               // x points to j, so j = 3

    printf("i = %d, j = %d", i, j); // i = 1, j = 3
}

答案 1 :(得分:-1)

假设“y”在您的情况下表示“j”,因为您提到“y”更改为3并且您的代码中没有其他任何内容将其值更改为3:

在上面的行中(* x)= 3;你有x =& j;这使得x指向j。现在你取消引用x并改变它所指向的值,那就是j。