使用指针指针更改引用

时间:2014-10-06 11:27:45

标签: c pointers

在下面的代码中,预期输出为1.但它是2.参考如何改变?

#include <stdio.h>

int main()
{
    int a = 1, b = 2, c = 3;
    int *ptr1 = &a, *ptr2 = &b, *ptr3 = &c;
    int **sptr = &ptr1; //-Ref
    *sptr = ptr2;
    printf("%d",*ptr1);
}

2 个答案:

答案 0 :(得分:3)

int a = 1, b = 2, c = 3;
int *ptr1 = &a, *ptr2 = &b, *ptr3 = &c; 

ptr1的值为a的地址,ptr2的值为b的地址。

int **sptr = &ptr1; // sptr has address of ptr1

由于sptr指向ptr1(其值为ptr1的地址),使用*sptr我们可以更改值ptr1

*sptr = ptr2; //here we are altering contents of sptr and value of ptr1.

现在ptr1指向ptr2所在的位置。至b = 2;

答案 1 :(得分:1)

int main()
{
    int a = 1, b = 2, c = 3;
    int *ptr1 = &a, *ptr2 = &b, *ptr3 = &c; 

    // ptr1 points to a 
    // ptr2 points to b



    int **sptr = &ptr1; //-Ref
    // *sptr points to ptr1 , that means **sptr points indirectly to a

    *sptr = ptr2; //this translates in ptr1 = ptr2, that means ptr1 points to what ptr2 pointed 
    return 0;
}