初始指针及使用示例
// chapter09a01指针.cpp :
//指针(pointer)是一个值为内存地址的变量(或数据类型)
//数据类型 *指针变量名; (int *ptrYear; ptrYear = &year)
//为指针赋值,赋值运算符右侧必须是一个地址
//1.如果是普通变量需要在前面加一个取地址运算符 & ;
//2.如果是另一个指针变量或者是一个数组,不需要加 & 运算符
//运算符 * 用于返回指针指向的内存地址中存储的值
//使用指针访问一维数组和二维数组的元素
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
double num = 1024.5;
double* ptr_num = # //申明一个指针,指向num变量
cout << "ptr_num的值:"<< ptr_num << endl;
cout << "ptr_num指向空间的值是:" << *ptr_num << endl;
*ptr_num = 1111; //对num进行修改
cout << num << endl;
char ch = 'a';
char* ptr_ch = &ch;
cout << (void *)ptr_ch << endl; // void * 任意类型
cout << *ptr_ch << endl;
}
空指针和 void 指针*
// chapter09a02常见指针类型.cpp :
//1.空指针:不指向任何对象,在试图使用一个指针之前可以先检查是否为空
//用法 int* ptr1 = nullptr;
//2. void*指针 :一种特殊的指针类型,可以存放任意对象的地址
//一般用来跟别的指针进行比较,作为函数的输入和输出:赋值给另一个 void* 指针
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
double * ptr_double = nullptr; //初始化指针
cout << ptr_double <<endl; //00000000
double objNum = 3.14;
double* ptr_obj1 = &objNum;
void* ptr_obj2 = &objNum;
cout << ptr_obj1 <<endl;
cout << ptr_obj2 << endl;
cout << boolalpha;
cout << (ptr_obj1 == ptr_obj2) << endl;
*ptr_obj1 = 210;
cout << objNum << endl;
}