C 语言中常量指针是什么意思?


指针地址的值为常量,这意味着我们不能更改指针所指地址的值。

常量指针声明如下 −

Data_Type const* Pointer_Name;

例如,int const *p// 指向常量整数的指针

示例

以下是 C 程序,用于说明指向常量的指针 −

#include<stdio.h>
int main(void){
   int var1 = 100;
   // pointer to constant integer
   const int* ptr = &var1;
   //try to modify the value of pointed address
   *ptr = 10;
   printf("%d
", *ptr);    return 0; }

输出

当执行上述程序时,将产生以下结果 −

Display error, trying to change the value of pointer to constant integer

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

以下 C 程序演示了去掉 const 的效果 −

 现场演示

#include<stdio.h>
int main(void){
   int var1 = 100;
   // removed the pointer to constant integer
   int* ptr = &var1;
   //try to modify the value of pointed address
   *ptr = 10;
   printf("%d
", *ptr);    return 0; }

输出

当执行上述程序时,将产生以下结果 −

10

更新于:08-3-2021

594 次浏览

开启你的 职业 生涯

通过完成课程,获得认证

开始
广告