首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么这个常量char*在实际修改后不能修改?

为什么这个常量char*在实际修改后不能修改?
EN

Stack Overflow用户
提问于 2019-03-05 04:19:10
回答 2查看 89关注 0票数 0

举个例子:

代码语言:javascript
复制
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*,并且我能够为它重新分配另一个值(内存中的实际数据-而不是内存地址本身)。

但是,它告诉我,我不能改变在第四个位置的字符!

为什么会这样呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-05 04:22:09

在这段代码中,what是指向const char的非常数指针。

您可以更改what,但不能更改*what

如果你想声明一个指向const char的常量指针,你需要写两次const

代码语言:javascript
复制
const char *const what = "Is This";
// what is const
what = "Interesting"; // Error
// *what is also const
what[4] = 'x';        // Error

如果你想要一个指向非常数字符的常量指针,可以把它写在不同的地方:

代码语言:javascript
复制
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
票数 6
EN

Stack Overflow用户

发布于 2019-03-05 04:21:24

const应用于所指向的字符,而不是指针本身!所以你可以指向任何你想要的C字符串,但是不能改变这些字符串的字符。

为了简单起见,我将使用另一种类型来说明这一点(C字符串文字不能修改):

你实际上有像这样的东西

代码语言:javascript
复制
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指向的指针:

代码语言:javascript
复制
int i = 666;
int j = 999;
int *const pi = &i;
*pi = 999;
// pi = &j; is invalid, pi will always point to i

然后你可以将两者混合在一起,永远不要改变指针或int指针:

代码语言:javascript
复制
const int i = 666;
const int j = 999;
const int *const pi = &i;
// pi = &j; is invalid
// *pi = 444; is invalid
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54990928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档