【问题标题】:Why should I use pointers? C++为什么要使用指针? C++
【发布时间】:2015-11-11 14:59:17
【问题描述】:

我对 c++ 有点陌生,但我不明白为什么要使用指针和引用?

例如,我不明白这是如何工作的

int a = 8;
int *p1;
p1 = &a;

【问题讨论】:

  • 你没有得到什么?这是非常基础的,在很多地方都有讨论,包括你的教科书/参考手册。
  • @NathanOliver 是正确的,这已经讨论过很多次了。我建议快速谷歌搜索和阅读文档,如this
  • 您的意思是“我不明白它为什么有效”还是说“我看不出它的价值”?

标签: c++ pointers reference


【解决方案1】:

指针是变量的地址。

将 ram 想象成连续的盒子。每个盒子都有一个地址。

现在在你的例子中。

int a = 8; //declares a variable of type int and initializes it with value 8

int *p1; //p1 is a pointer meaning that the variable p1 holds an address instead of a value.

p1 = &a; //The operator &is called address of. This statement makes p1 point to the address of a. That is p1 holds the address of a.

为了访问 a 的值而不是地址,您需要尊重它。

*p1 = 9; //now a = 9

【讨论】:

  • 指针并不总是变量的地址,它可以是指向数组中元素的指针、指向易失性内存位置的指针等。
  • @TartanLlama 数组的元素有一个地址,通过将该地址分配给一个指针,只不过是该元素的地址。好吧,在扩展中,我们称它为指向数组元素的指针,但它仍然是一个地址。是的,你可以有指向指针等的指针,我只是想举一个非常简单的例子。
猜你喜欢
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2014-01-04
相关资源
最近更新 更多