我为什么要使用指针? C ++

时间:2015-11-11 14:59:17

标签: c++ pointers reference

我是c ++的新手,我不知道为什么我应该使用指针和引用?

例如,我不知道这是如何工作的

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

1 个答案:

答案 0 :(得分:0)

指针是变量的地址。

想象一下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