举个例子:
int main()
{
const char* what = "Is This";
what = "Interesting";
cout << *what;
what[3] = 'a'; // Sytax Error: expression must be a modifiable lvalue
cout << *what;
return 0;
}
因此,我将what
声明为const char*
,并且我能够为它重新分配另一个值(内存中的实际数据-而不是内存地址本身)。
但是,它告诉我,我不能改变在第四个位置的字符!
为什么会这样呢?
发布于 2019-03-05 04:22:09
在这段代码中,what
是指向const char的非常数指针。
您可以更改what
,但不能更改*what
。
如果你想声明一个指向const char的常量指针,你需要写两次const
:
const char *const what = "Is This";
// what is const
what = "Interesting"; // Error
// *what is also const
what[4] = 'x'; // Error
如果你想要一个指向非常数字符的常量指针,可以把它写在不同的地方:
char isthis[] = "Is This";
char interesting[] = "Interesting";
char *const what = isthis;
// what is const
what = interesting; // Error
// *what is not const
what[4] = 'x'; // Ok
发布于 2019-03-05 04:21:24
const
应用于所指向的字符,而不是指针本身!所以你可以指向任何你想要的C字符串,但是不能改变这些字符串的字符。
为了简单起见,我将使用另一种类型来说明这一点(C字符串文字不能修改):
你实际上有像这样的东西
const int i = 666;
const int j = 999;
const int *pi = &i;
pi = &j;
// *pi=444; is invalid, can't change the int pointed by pi
您可以构建一个不能更改但int指向的指针:
int i = 666;
int j = 999;
int *const pi = &i;
*pi = 999;
// pi = &j; is invalid, pi will always point to i
然后你可以将两者混合在一起,永远不要改变指针或int指针:
const int i = 666;
const int j = 999;
const int *const pi = &i;
// pi = &j; is invalid
// *pi = 444; is invalid
https://stackoverflow.com/questions/54990928
复制相似问题