c – 这个2 const意味着什么?

码:

const char * const key; 

上面的指针有2个const,我第一次看到这样的东西。

我知道第一个const使指针指向的值不可变,但第二个const是否使指针本身不可变?

有人可以帮忙解释一下吗?


@Update:

我写了一个程序,certificate答案是正确的。

 #include  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个函数中的行,将得到编译错误提示。

第一个const告诉你不能改变*keykey[i]

以下行无效

 *key = 'a'; *(key + 2) = 'b'; key[i] = 'c'; 

第二个const告诉你不能改变key

以下行无效

 key = newkey; ++key; 

另请查看如何阅读此复杂声明


添加更多细节。

  1. const char *key :您可以更改密钥但不能更改密钥指向的字符。
  2. char *const key :你不能改变键,但是键可以指向chars
  3. const char *const key :你不能改变键和指针字符。

const [type]*表示它是一个不改变指向值的指针。 [type]* const表示指针本身的值不能改变,即它保持指向相同的值,类似于Java final关键字。