在下面的代码中,预期输出为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);
}
答案 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;
}