C語言中 const char* p、char * const p 和 const char * const p 的區別


指標

在 C 程式語言中,*p 表示儲存在指標中的值,而 p 表示該值的地址,被稱為指標。

const char*char const* 表示指標可以指向一個常量字元,並且該指標指向的字元的值不能更改。但是我們可以更改指標的值,因為它不是常量,並且可以指向另一個常量字元。

char* const 表示指標可以指向一個字元,並且該指標指向的字元的值可以更改。但是我們不能更改指標的值,因為它現在是常量,並且不能指向另一個字元。

const char* const 表示指標可以指向一個常量字元,並且該指標指向的 int 值不能更改。並且我們也不能更改指標的值,因為它現在是常量,並且不能指向另一個常量字元。

經驗法則是從右到左命名語法。

// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *

示例(C)

取消註釋錯誤程式碼並檢視錯誤。

 線上演示

#include <stdio.h>
int main() {
   //Example: char const*
   //Note: char const* is same as const char*
   const char p = 'A';
   // q is a pointer to const char
   char const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 'B';
   const char r = 'C';
   //q can point to another const char
   q = &r;
   printf("%c
", *q);    //Example: char* const    char u = 'D';    char * const t = &u;    //You can change the value    *t = 'E';    printf("%c", *t);    // Invalid asssignment    // t cannot be changed    // error: assignment of read-only variable 't'    //t = &r;    //Example: char const* const    char const* const s = &p;    // Invalid asssignment    // value of s cannot be changed    // error: assignment of read-only location '*s'    // *s = 'D';    // Invalid asssignment    // s cannot be changed    // error: assignment of read-only variable 's'    // s = &r;    return 0; }

輸出

C
E

更新於: 2020年1月6日

12K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.