主要内容
在今天的大师码课程中,我们要介绍指针。
指针,和之前提到的变量地址,有着非常重要的关系。
1. 输出地址
学习到现在,希望大家的心中,要有一个这样的变量模型。

在这个变量模型中,应该有两个部分
地址
数值
注意:以后我们谈到【变量】,大家脑海中一定要有这样的两个部分【地址】和【数值】。
我们已经知道,如何输出变量的数值,那么,如何输出变量的地址呢?
#include < iostream >
using namespace std;
int main()
{
int dashima(50);
cout << "dashima 的数值为:" << dashima << endl;
cout << "dashima 的地址为:" << &dashima << endl; // 【注意】 & 符号
return 0;
}
C++ 中使用
符号(&)表示表示变量的地址。该符号称为
“取地址符”。
那么,一个很自然的问题就来了,【数值】可以用【数值类型的变量】来存储;那么,指针呢?
请看代码
2. 指针类型
int dashima(50);
int * p = &dashima; // int * ,表示 int 类型的指针
C++ 中,指针需要使用
符号(*)来表示。
如上面的代码中 int * p ,一般我们就称
“p 是 int 类型的指针”。
请注意。指针的英文为:pointer,所以,我们习惯上将指针变量,命名为 p,或者以 p开头。这是一个比较好的习惯。
比如
int dashima(50);
int * p = &dashima;
int * pDashima = &dashima;
int * p_dashima = &dashima;
3. 指针模型

注意:
【指针】其实也是【变量】
【指针变量】也有地址
【指针变量】的数值,是一个地址,(就是那个普通变量的地址)。
指针在赋值的时候,是将变量的地址,写入到指针的值中。如上图所示,请特别注意!
4. 小结
和数组类似,指针也有不同的类型,比如
char * pDashima_c ;
short * pDashima_s ;
int * pDashima_i ;
long * pDashima_l ;
long long * pDashima_ll ;
float * pDashima_f ;
double * pDashima_d ;
long double * pDashima_ld ;
unsigned char * pDashima_uc ;
unsigned short * pDashima_us ;
unsigned int * pDashima_ui ;
unsigned long * pDashima_ul ;
unsigned long long * pDashima_ull;
指针和数组,都可以看作是基本类型的扩展。
这里,我们可以把变量指针和之前的大师码课程的内容串联起来,给大家梳理【数据类型】【数组】【指针】之间的关系。
// 以 int 为例
基础类型 | 拓展 1 - 数组 | 拓展 2 - 指针|
int | int[] | int * |
变量 | 数组变量 | 指针变量 |
习题
课后练习