const和指针
来源:互联网 发布:64码高清网络电视 手机 编辑:程序博客网 时间:2024/05/17 19:56
1.指针和const:
a. 指针指向一个常量对象,这样可以防止使用该指针来修改所指向的值。
b. 将指针本身声明为常量,这样可以防止改变指针指向的位置。
实例1:声明一个指向常量的指针pt:
int age = 39;
const int * pt = &age;
该声明指出:pt是指向一个const int(这里是39),因此不能使用pt来修改这个值;换句话说:*pt的值为const,不能被修改。
实例2:将常规变量的地址赋值给指向const的指针:
a. 将const变量的地址赋值给指向const的指针;(合法可行)
const float g_earth = 9.80;
const float *pe = &g_earth;
注:既不能使用g_erath来修改值9.80,也不能使用pe来修改。
b. 将const的地址赋值给常规指针。(不可行的)
const float g_earth = 9.80;
float *pe = &g_earth;
注:可以使用pe来修稿g_earth的值,这和g_earth是const变量矛盾。
实例3:指针指向指针
a. 涉及的是一级间接关系,则将非const赋值给const指针是可以得;
int age = 39;
int *pd = &age;
const int *pt = pd;
b. 进入两级间接关系时,将const和非const混合的指针赋值方式将不再安全。如果允许,编写代码如下:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1;
*pp2 = &n;
*p1 = 10;
注:上述代码将非const地址(&p1)赋给const指针(pp2),因此可以使用p1来修改const数据。因此,仅当只有一层间接关系时,才可以将非const地址或指针赋给const指针。
实例4:const数组
禁止将常量数组的地址复制给非常量指针,同时意味着不能将数组名作为参数传递给使用非常量的函数。
const int months[12] = {31,28,31,30,31,30};
int sum(int arr[],int n);
Int sum = sum(months,12);
注:最后一行代码执行的过程中会报错,原因是因为函数的参数是一个非常量指针的形参,而数组months是一个常量数组
- const引用和const指针
- const指针和const引用
- const数据和const指针
- 指向const的指针和const指针
- const对象的指针和const指针
- const指针和指向const的指针
- 指向const的指针和const指针
- 【C和指针】const指针
- 指针和const
- const和指针
- 指针和const
- const和指针
- const 和 指针
- 关于const和指针
- const和指针
- const和指针
- 指针和const
- const和指针
- 如何在Windows server上使用Node.js正常运行ZMQ库
- 整数的2的幂分解
- QFileInfo使用整理
- Oracle IN条件包含查询出来的列表和固定值的查询语句
- Ubuntu网络配置
- const和指针
- 使用.NET Reflector单步调试编译好的程序集
- C++ primer 读书笔记一
- UVA 11583 Partitioning by Palindromes (区间DP)
- BZOJ 4278: [ONTAK2015]Tasowanie 后缀数组
- 设计模式(4)--原型模式
- 欢迎使用CSDN-markdown编辑器
- C语言中EOF是什么意思?
- PHP入门资料