#include <stdlib.h>
#include <stdio.h>
void show_array(const double ar[], int n);
void mult_array_one(double ar[], int n);
void mult_array_two(const double ar[], int n);
int main(int argc, char const *argv[])
{
/*
1、指针常量和常指针
*/
double rate[5] = {10.11,20.12,30.44,50.32,70.32};
//常量指针,常指针,即指向的数据是一个常量,值不能变
const double *p1 = rate;
//指针常量,即指针是一个常量,地址不能变
double * const p2 = rate;
printf("原首元素:%f\n",p1[0]);
//p1[0] = 33;//错误
p2[0] = 90;
printf("现首元素:%f\n",rate[0]);
printf("原地址:%p\n",rate);
//p2 = &rate[2];//错误
p1 = &rate[2];
printf("现地址:%p\n",p1);
/*
2、非const数据的地址只能赋值给普通指针,不能赋值const指针,否则就能通过指针改变const数组的数据
*/
const double lock[5] = {2.1,3.4,23.11,23.55,89.33};
const double *t1 = lock;
//double *t2 = lock;//错误
/*
3、const修饰形参,保护传入形参的值不被改变,即只读
*/
double sea[5] = {2.1,3.4,23.11,23.55,89.33};
mult_array_two(sea,5);
show_array(sea,5);
mult_array_one(sea,5);
show_array(sea,5);
return 0;
}
void test_const()
{
const int y = 10;
const int *p = &y;
int *q;
/*
4、const指针赋值给非const指针,C发出警告,C++会报错
*/
q = p;
*q = 20; //通过非const指针修改const值,该行为未定义
printf("%d ",*q);
}
void show_array(const double ar[], int n)
{
int i;
for(int i=0; i<n; i++){
printf("%8.3f ", ar[i]);
}
putchar('\n');
}
void mult_array_one(double ar[], int n)
{
double sum = 0;
for(int i=0; i<n; i++){
sum += ar[i]++;//ar[]数组中的值被改变
}
printf("%f\n",sum);
}
void mult_array_two(const double ar[], int n)
{
double sum = 0;
for(int i=0; i<n; i++){
//sum += ar[i]++;//报错:ar[] is read-only
}
printf("%f\n",sum);
}
const用法
最新推荐文章于 2021-10-20 02:04:08 发布