C艹 指针和const的关系和注意事项(非常有意思)

有两种不同的形式将const关键字指向指针。

第一种:让指针指向一个常量对象

const float g_moon = 1.63;
float * pm = &g_moon; // 不允许 no allowed

第二种: 是将指针本身声明为常量

声明一个指向常量的指针pt

int age = 39;
const int *pt = &age;

这个声明表示, pt指向一个const int, 但不能使用*pt来修改age的值;

但是可以修改指向的内存地址

int sum = 200;
p = ∑

注意,有种情况不允许:

const float g_earth = 9.80;
const float * pe = &g_earth; // 允许

const float g_moon = 1.63;
float * pm = &g_moon; // 不允许 no allowed

=======================================

另一种方式:

int sloth = 3;
const int * ps = &loth;
int * const finger = &sloth; //说明优势

优势:

*finger = 20;

猜你喜欢

转载自www.cnblogs.com/renfanzi/p/7511515.html