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

示例

以下 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 次瀏覽

開啟你的 職業 生涯

透過完成課程,獲得認證

開始
廣告
© . All rights reserved.