指针(pointer)
简介:指针是一个值为内存地址的变量(或数据对象)
声明
数据类型 * 指针变量名
例:
int* ptr_num;
char* ptr_name;
...
int year;
year=2016;
int * ptr_year;
//取地址符&
ptr_year=&year; //赋值内存地址
输出char类型的时候需要强转成void *
char ch='a';
char* ptr_ch=&ch;
cout << (void *)ptr_ch << '\t' << *ptr_ch << endl;
空指针(null pointer)
空指针不指向任何对象,在试图使用一个指针之前首先检查是否为空
用法
int* ptr1=nullptr;//=0
int* ptr2=0; //直接初始化字面量常量0
//需要包含头文件cstdlib
int* ptr3=NULL;
//如果不给指针赋值他会有默认的地址(野指针)
void*指针
一种特殊类型的指针类型,可以存放任意对象的地址
double num=3.14;
double* ptr_num1=#
void* prt_num2=#
cout << boolalpha;
cout << (ptr_num1==ptr_num2) << endl; //1 true
//void*类型不能确定多数用于比较和输出