//9 – 4 null pointer and wild pointer
#include <iostream>
using namespace std;
int main() {
//1.null pointer(空指针)
//normally,if we don’t use the pointer, we will define it null
int* p = NULL;
//but it we dereference it, it will be a null pointer error
//cout << *p << endl;
//2.wild pointer(野指针)
int* pa = (int*)0x121412;
//force translate the RAM address to int * type pointer and assigned it
//wild pointer:define a ramdon number to the pointer casually
cout << *pa << endl;
//if the code cost a lot time, it probably an error exists
return 0;
}
//9-5-1 pointer constant(指针常量)
#include <iostream>
using namespace std;
/*
the relationship between constant and pointer:
*/
int main() {
int a = 1;
int b = 2;
//pointer constant
//the value of the pointer is a constant, the value is an address now
int* const p = &a;
//p = &b; //it don’t allow to change it
*p = 7;//but the value that pointer pointed to(dereference) can be modified
cout << “a = ” << a << endl;
return 0;
}
//9 – 5 – 3 const pointer to a const
#include <iostream>
using namespace std;
/*
指针常量 type* const 指针值是一个常量 指针无法被赋值
常量指针 const type* 指向常量的指针 指针解引用后无法被赋值
常量指针常量 const type* const 指针值和指针指向的值都是常量 指针和解引用都无法被赋值
*/
int main() {
int a = 1;
int b = 2;
//常量指针常量:本身的值和指向的地址中的值都无法改变
const int* const p = &a;
//*p = 6; //error
//p = &b;//error
return 0;
}
AI:
指针常量(pointer constant)和常量指针(pointer to a constant)是 C/C++ 中容易混淆的两个概念,核心区别在于 **“不可变” 的对象不同 **:
1. 指针常量(pointer constant)
- 定义:指针本身是一个常量,指针存储的地址不能被修改,但指针指向的内容可以修改。
 - 语法形式:类型* const 指针名;
例:int* const p;(p 是指针常量) - 特性:
- 指针一旦初始化(指向某个地址),就不能再指向其他地址(p = &a; 初始化后,p = &b; 会报错)。
 - 可以通过指针修改指向的内容(*p = 10; 合法)。
 
 
2. 常量指针(pointer to a constant)
- 定义:指针指向的是一个常量,通过该指针不能修改指向的内容,但指针本身可以指向其他地址。
 - 语法形式:const 类型* 指针名; 或 类型 const* 指针名;(两种写法等价)
例:const int* p; 或 int const* p;(p 是常量指针) - 特性:
- 指针可以随时改变指向(p = &a; 之后,p = &b; 合法)。
 - 不能通过指针修改指向的内容(*p = 10; 会报错)。
 
 
一句话总结
- 指针常量:指针不可变,内容可变(int* const p;)。
 - 常量指针:内容不可变,指针可变(const int* p;)。
 
记忆技巧:看 const 修饰的是谁 —— 修饰指针(* 后)则是指针常量,修饰类型(* 前)则是常量指针。