『c専門家プログラミング』ノート--const char*p,char const*p,char*const pを深く理解する


const char*,char const*,char*constの違いはほとんどC++面接で毎回あるテーマです. 
実際、この概念は誰にでもあるが、3つの声明方式が非常に似ていて覚えやすい. 
Bjarneは彼のThe C++Programming Languageの中で助記の方法を与えたことがある.
声明を右から左に読む. 
char * const cp; (*pointer toと読む)
cp is a const pointer to char 
const char * p; 
p is a pointer to const char; 
char const * p; 
同様にC++にはconst*の演算子がないため、constは前のタイプに属するしかありません.
 
C++標準では、constキーワードはタイプまたは変数名の前に等価であることが規定されています.
char**p、const char**pのタイプ適合性の問題について
    1.に質問
        char *p1;const *p2=p1;//合法的
        char **p1;const  char**p2=p1;//不正な警告warning:initialization from incompatible pointer type
        char **p1;char const**p2=p1;//不正な警告warning:initialization from incompatible pointer type
        char**p1;char*const*p2=p1;//合法的
    2.判定ルール
const修飾の対象を明確に!ポインタp 1,p 2について、p 2=p 1を成立させるには、以下のように読むことができる.
「p 1はXタイプへのポインタであり、p 2は「const制限付き」のXタイプへのポインタである」.
        char *p1;const char *p2=p1;//合法:p 1は(char)タイプを指すポインタであり、p 2は「const限定」付き(char)タイプを指すポインタである.
        char **p1;const  char**p2=p1;//不正:p 1は(char*)タイプを指すポインタであり、p 2は(const char)*)タイプを指すポインタである.
        char **p1;char const**p2=p1;//合法ではない.上と等価.
        char**p1;char*const*p2=p1;//合法:p 1は(char*)タイプを指すポインタであり、p 2は「const限定」付き(char*)タイプを指すポインタである.
最後の例:
#include <stdio.h>

int main(void){

        int v1 = 1;
        int v2 = 2;

        int const *a = &v1;
        *a = 2;

        int *const b = &v2;
        b = &v1;

        char**p1;
        char*const*p2=p1;
        *p2 = &v1;

        return 0;
}
コンパイル中に次のエラーが発生しました.
const.c: In function 'main':
const.c:9: error: assignment of read-only location '*a'
const.c:12: error: assignment of read-only variable 'b'
const.c:16: error: assignment of read-only location '*p2'