コード:
const char * const key;
上記のポインターには 2 つの const があり、このようなものは初めて見ました。
最初の const がポインターが指す値を不変にすることは知っていますが、2 番目の const はポインター自体を不変にしましたか?
誰でもこれを説明できますか?
@アップデート:
そして、その答えが正しいことを証明するプログラムを書きました。
#include <stdio.h>
void testNoConstPoiner() {
int i = 10;
int *pi = &i;
(*pi)++;
printf("%d\n", i);
}
void testPreConstPoinerChangePointedValue() {
int i = 10;
const int *pi = &i;
// this line will compile error
// (*pi)++;
printf("%d\n", *pi);
}
void testPreConstPoinerChangePointer() {
int i = 10;
int j = 20;
const int *pi = &i;
pi = &j;
printf("%d\n", *pi);
}
void testAfterConstPoinerChangePointedValue() {
int i = 10;
int * const pi = &i;
(*pi)++;
printf("%d\n", *pi);
}
void testAfterConstPoinerChangePointer() {
int i = 10;
int j = 20;
int * const pi = &i;
// this line will compile error
// pi = &j
printf("%d\n", *pi);
}
void testDoublePoiner() {
int i = 10;
int j = 20;
const int * const pi = &i;
// both of following 2 lines will compile error
// (*pi)++;
// pi = &j
printf("%d\n", *pi);
}
int main(int argc, char * argv[]) {
testNoConstPoiner();
testPreConstPoinerChangePointedValue();
testPreConstPoinerChangePointer();
testAfterConstPoinerChangePointedValue();
testAfterConstPoinerChangePointer();
testDoublePoiner();
}
3 つの関数の行のコメントを外すと、コンパイル エラーが発生し、ヒントが表示されます。