代码:
const char * const key;
上面的指针中有 2 个 const,我第一次看到这样的东西。
我知道第一个 const 使指针指向的值不可变,但是第二个 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 个函数中的行,将得到带有提示的编译错误。