Ç - 这是什么2常量是什么意思? [英] c - what does this 2 const mean?
本文介绍了Ç - 这是什么2常量是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
code:
const char * const key;
有上述指针2常量,我看到了这样的事情还是第一次。
There are 2 const in above pointer, I saw things like this the first time.
我认识的第一个常量使得由指针指向永恒不变的价值,
但没有第二个常量使指针本身不可变的?
I know the first const makes the value pointed by the pointer immutable, but did the second const make the pointer itself immutable?
任何人都可以帮助解释一下吗?
Anyone can help to explain this?
@Update:
和我写的证明,答案是正确的程序。
And I wrote a program that proved the answer is correct.
#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取消注释行,将得到编译错误与技巧。
Uncomment lines in 3 of the functions, will get compile error with tips.
推荐答案
首先常量是为了告诉你不能改变 *键
,键[I]
等
First const tells you can not change *key
, key[i]
etc
以下行的无效
*key = 'a';
*(key + 2) = 'b';
key[i] = 'c';
二常量告诉你不能改变键
以下行的无效
key = newkey;
++key;
另外,请查阅如何读
添加更多的细节。
-
为const char *键
:你可以改变的关键,但不能更改键指向的字符 -
char * const的关键
:你不能改变的关键,但可以通过按键 指出的字符 -
为const char * const的关键
:您不能更改密钥以及指针字符
const char *key
: you can change key but can not change the chars pointed by key.char *const key
: You can not change key but can the chars pointed by keyconst char *const key
: You can not change the key as well as the pointer chars.
这篇关于Ç - 这是什么2常量是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文