C 指针赋值

新手上路,请多包涵

为什么是 90 yq --- 的输出值?我只是做 p=qq 的值怎么变了?

 int main()
{

    int x;
    int y;
    int *p = &x;
    int *q = &y;

    x = 35;
    y = 46;

    p = q;

    *p = 90;

    cout << x << " " << y << endl;
    cout << *p << " " << *q << endl;
    cout << "Address of p = " << p << endl;
    cout << "Address of q = " << q << endl;

    return 0;
}

输出是:

 35 90
90 90
Address of p = 0xbffa83c0
Address of q = 0xbffa83c0

原文由 Fusionmate 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 395
2 个回答

我想分享一个通用技术,当我开始学习指针的工作原理时,我使用该技术。如果你把它应用到你的问题上,你会看到答案一清二楚。

拿一张大方格纸,将它纵向放在你面前的桌子上。这是您计算机的内存。每个框代表一个字节。选择一行,然后将数字“100”放在最左边的框下方。这是内存的“最低地址”。 (我选择了 100 作为非 0 的任意数字,您可以选择另一个。)从左到右按升序对框进行编号。

+---+---+---+---+---+--
| | | | | | ...
+---+---+---+---+---+--
100 101 102 103 104 ...

现在,暂时假设一个 int 大小为一个字节。你是一台八位计算机。将您的 int a 写入其中一个框中。方框下方的数字是它的地址。现在选择另一个框来包含 int *b = &aint *b 也是存储在内存某处的变量,它是一个包含 &a 的指针,读作“a的地址”。

 int  a = 5;
int *b = &a;

  抗体
+---+---+---+---+---+--
| 5 | |100| | | ...
+---+---+---+---+---+--
 100 101 102 103 104 ...

现在,您可以使用此模型直观地处理您看到的任何其他值和指针组合。这是一种简化(因为正如语言学究所说,指针 不一定 是地址,内存也不 一定 是顺序的,还有堆栈和堆和寄存器等等),但对于 99% 来说,这是一个很好的类比计算机和微控制器。

所以在你的情况下,

 int x = 35;
int y = 46;

  xy
+---+---+---+---+---+--
| 35| 46| | | | ...
+---+---+---+---+---+--
 100 101 102 103 104 ...

int *p = &x;
int *q = &y;

  xypq
+---+---+---+---+---+--
| 35| 46|100|101| | ...
+---+---+---+---+---+--
 100 101 102 103 104 ...

p = q;

  xypq
+---+---+---+---+---+--
| 35| 46|101|101| | ...
+---+---+---+---+---+--
 100 101 102 103 104 ...

*p = 90;

  xypq
+---+---+---+---+---+--
| 35| 90|101|101| | ...
+---+---+---+---+---+--
 100 101 102 103 104 ...

现在 *p 是什么?什么是 *q

原文由 Crashworks 发布,翻译遵循 CC BY-SA 3.0 许可协议

int main()
{

    int x;
    int y;
    int *p = &x;//this p pointer stores address of variable x
    int *q = &y;//this q pointer stores address of variable y

    x = 35;//assigned value 35 to x
    y = 46;//assigned value 46 to y

    p = q;//this line make pointer p to store address which is their in q that is address of y

    *p = 90;//this line will change the value of y because by previous we change the pointer p address before line p=q p was pointing to x but now it is pointing to y

    cout << x << " " << y << endl;
    cout << *p << " " << *q << endl;as we make pointers p and q pointing to same variable that is y and change the value of y to 90 by doing*p=90 output for both *p & *q is 90
    cout << "Address of p = " << p << endl;
    cout << "Address of q = " << q << endl;

    return 0;
}

原文由 Satyam Tripathi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏